Python call c / c ++ function

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:

  1. = 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.
  2. 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:

  1. https://stackoverflow.com/questions/22391229/ctypes-returns-wrong-result
  2. https://docs.python.org/3/library/ctypes.html
Published 36 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/wang_jun_whu/article/details/99111928