允许从Python中调用C++函数、使用C++类和对象的库PyCXX

PyCXX是一个可以让Python嵌入C++的库。它允许从Python中调用C++函数、使用C++类和对象等。

PyCXX主要提供以下功能:

  • 创建C++类的Python封装:
class Vector:
    Vector(int n): n(n){}
    int n;
    double operator[](int i) {return 0;}

PYTHON_WRAPPER(Vector) {
     PYTHON_INIT(int n)
     PYTHON_INDEX(double,operator[],int)   
}
  • 从Python调用C++函数:
double sum(double a, double b) {
    return a + b;
}

PYTHON_MODULE(math, m) {    
    m.def("sum", &sum);
}  
  • 枚举类型的绑定:
enum Fruit {Apple, Orange};

PYTHON_ENUM(Fruit) {
     {"Apple",Apple},
     {"Orange",Orange}
};    
  • 为C++异常增加Python处理器
  • 等等。

主要使用步骤是:

  1. 使用提供的宏编写C++代码
  2. 使用提供的脚本编译生成_pycxxbind.cpp文件
  3. 编译生成_pycxxbind.so库文件
  4. 在Python中导入该modul

猜你喜欢

转载自blog.csdn.net/zhangzhechun/article/details/131589483