Python中调用c/c++函数

Python中调用c/c++函数.
Python的编码速度无疑要高于C++,但有些时候,我们不得不使用C++的某些库,这个时候,可以使用Python调用c/c++的功能来实现.
C/C++部分
首先定义一个类

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 部分

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()

值得注意的点:

  1. lib.Foo_bar.argtypes = [ctypes.c_double]
    lib.Foo_bar.restype = ctypes.c_double
    指定返回值时,主要使用的是restype.指定参数时,Foo* cb, 不需要算在内,直接制定第二个即可.
  2. 在python中调用时,并不需要对类对象进行self.obj的指定lib.Foo_bar(ctypes.c_double(10.1))).
    C++中的编译:
    set (CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/…/)
    add_library(test_lib SHARED test.cpp)

参考资料:

  1. https://stackoverflow.com/questions/22391229/ctypes-returns-wrong-result
  2. https://docs.python.org/3/library/ctypes.html
发布了36 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wang_jun_whu/article/details/99111928