Python calls C ++ code
This document describes how to call C ++ using python using the instance code.
1. if no parameters are passed from python to C ++, the simplest way for python to call C ++ is to declare the function as a C Available function and then be called as a C code by python, as shown on the third floor;
2. swig is the most convenient method to call when parameters are passed to the C ++ function, as shown in the following project;
Rachel. I (swig file ):
%module rachel%{#include rachel.h%}extern int linear(int x, int w, int b);
C ++ code:
Rachel. h:
#include
#include
int linear(int x, int w, int b);
Rachel. cpp:
#include rachel.h int linear(int x, int w, int b){ int res = w * x + b; printf(%d, res); return res; }
Run the following command:
swig -c++ -python rachel.ig++ -c -fPIC rachel_wrap.cxx -I/home/zhangruiqing01/.jumbo/include/python2.7 -I./includeg++ -shared rachel.o rachel_wrap.o -o _rachel.so
In the first sentence, swig generates rachel_warp.cxx (if it is C, swig-python rachel. I is used to generate the rachel_warp.c file );
The last sentence generates the dynamic link library _ rachel. so for python calling (if it is C, use ld-shared rachel. o rachel_warp.o-o _ rachel. so );
Python call:
>>> import _rachel>>> _rachel.linear(1,2,5)7
Finally, let's take a look at the program structure in this article: