Python call c / c ++ functions.
Python coding rate undoubtedly higher than C ++, but sometimes we have to use some library of C ++, this time, you can use the Python calling c / c ++ functions to achieve.
C / C ++ section :
First define a class
class Foo{
public:
double x = 0;
public:
double bar(double t){
x = t;
std::cout << "c++ " << x << std::endl;
return x;
}
};
// 封装C接口
extern "C"{
// 创建对象
Cbacken* cbacken_new(){
return new Cbacken;
}
void cbacken_sort(Cbacken* cb, int *arr, int n){
cb->sort(arr, n);
}
Foo* Foo_new(){ return new Foo(); }
double Foo_bar(Foo* cb, double t){
double m = t;
cb->bar(m);
std::cout << "c " << m << "\n";
return m;
//return foo->bar();
}
}
python part :
class Foo(object):
def __init__(self):
self.obj = lib.Foo_new()
def bar(self):
lib.Foo_bar.argtypes = [ctypes.c_double]
lib.Foo_bar.restype = ctypes.c_double
print("python: ", lib.Foo_bar(ctypes.c_double(10.1)))
if __name__ == '__main__':
f = Foo()
f.bar()
It is noteworthy point:
- = lib.Foo_bar.argtypes [ctypes.c_double]
lib.Foo_bar.restype = ctypes.c_double
specified return value, mainly used restype. When specifying parameters, Foo * cb, do not need to taken into account, it can direct the development of a second. - When you call in python, does not need to be specified class object lib.Foo_bar self.obj of (ctypes.c_double (10.1))).
Compiler in C ++:
SET (CMAKE_LIBRARY_OUTPUT_DIRECTORY CMAKE_BINARY_DIR} {$ / ... /)
add_library (test_lib the SHARED test.cpp)
References: