使用pybind11实现Python环境下C++中间件的相关问题咨询
问题1 调用Python类成员方法的解决方案
你遇到的AttributeError是因为setValue是Driver类的成员方法,不是Driver.py模块的顶层函数,不能直接从模块层面调用,需要先实例化类再调用成员方法。同时你现有的pybind绑定逻辑也存在错误,具体修正步骤如下:
- 修正Middleware.h中的绑定逻辑:
testFunctionA是middleware类的非静态成员方法,不能直接绑定为全局函数,需要先绑定类结构:
#include <pybind11/pybind11.h> namespace py = pybind11; class middleware { public: unsigned int testFunctionA(const unsigned int n); }; PYBIND11_MODULE(pybind_11_example, mod) { py::class_<middleware>(mod, "middleware") .def(py::init<>()) .def("testFunctionA_cpp", &middleware::testFunctionA, "Middleware test function."); }
- 修正Middleware.cpp中的Python调用逻辑:
#include "Middleware.h" #include "stdio.h" #include <pybind11/pybind11.h> #include <pybind11/stl.h> unsigned int middleware::testFunctionA(const unsigned int n) { printf("Now Sent back to python driver interface\n"); py::module driver_module = py::module::import("Driver"); // 先拿到Driver类,再实例化 py::object DriverCls = driver_module.attr("Driver"); py::object driver_instance = DriverCls(); // 调用实例的成员方法 py::object result = driver_instance.attr("setValue")("setting value from cpp to python driver"); return 42; }
- 修正App.py的调用逻辑,先实例化中间件类再调用方法:
import pybind_11_example as middleware_cpp n = 40 print('C++:') mid = middleware_cpp.middleware() print('Answer:', mid.testFunctionA_cpp(n))
- 额外注意:运行前确保
Driver.py和App.py在同一工作目录,或者已经加入Python的模块搜索路径,否则会出现模块导入失败的问题。
问题2 解释器初始化问题解答
不需要调用py::scoped_interpreter guard{}。该接口仅用于C作为主入口程序主动启动Python解释器的场景,你当前是Python主进程调用C扩展模块,Python解释器已经处于运行状态,重复初始化会导致上下文冲突,你注释掉该行的操作是正确的。
内容的提问来源于stack exchange,提问作者Holger
相关产品推荐
相关产品推荐

