好吧,也許我找不到答案,因為我不確定如何表達,但我有一個名為 Info 的類和另一個名為 Packet 的類,它們都使用 boost 編譯成 Python 擴展,我想返回一個指向 Packet 模塊中的 Info 對象的指針。信息.cpp#include "info.h"Info::Info(int i_, int j_){ this->i = i_; this->j = j_;} Info::~Info(){}BOOST_PYTHON_MODULE(Info){ class_<Info>("Info", init<int, int>()) .def_readwrite("i", &Info::i) .def_readwrite("j", &Info::j);}數據包.cpp:Packet::Packet(int i_, int j_, PyObject* addr_, bool a_, bool b_){ this->i = i_; this->j - j_; this->addr = addr_; this->a = a_; this->b = b_;}// some other functionsInfo* Packet::test(){ return new Info(1,2);}BOOST_PYTHON_MODULE(Packet){ class_<Packet>("Packet", init<int, int, PyObject*, bool, bool>()) /*some other functions*/ .def("test", &Packet::test, return_value_policy<reference_existing_object>());}testPacket.py:from Packet import *# this works correctlyp = Packet(1,2, None, False, False)# this crashest = p.test()錯誤信息:Traceback (most recent call last): File "/usr/lib64/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib64/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/tmp/lirui/testPacket.py", line 5, in <module> print(p.test())TypeError: No Python class registered for C++ class Info有什么方法可以返回指向 Info 對象的指針嗎?
1 回答

撒科打諢
TA貢獻1934條經驗 獲得超2個贊
您只導入了Packet
.
您還需要導入Info
.
否則,如錯誤所述,Python 在嘗試使用它時無法識別它p.test()
(或者更具體地說,返回指向它的指針,分配給t
)。
添加回答
舉報
0/150
提交
取消