![](/img/trans.png)
[英]Boost::python - filling a C++ vector of pointer on object of a class in python
[英]How to return a pointer to a C++ object to python using boost if the class of that object is declared in another boost module?
好的,也许我没有找到答案,因为我不知道如何措辞,但我有一个名为 Info 的 class 和另一个名为 Packet 的 class ,两者都被编译成 ZA7F5F35426B927411FC9231B563821指向来自数据包模块的 Info object 的指针。
信息.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 functions
Info* 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>());
}
测试包.py:
from Packet import *
# this works correctly
p = Packet(1,2, None, False, False)
# this crashes
t = 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 object 的指针?
谢谢
您只导入了Packet
。
您还需要导入Info
。
否则,正如错误所说, Python 在p.test()
尝试使用它时无法识别它(或者,更具体地说,返回指向它的指针,分配给t
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.