如果在另一个 boost 模块中声明了该对象的 class,如何使用 boost return 指向 C++ 对象的指针 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?

好吧,也许我找不到答案,因为我不确定如何表达,但我有一个 class 称为 Info 和另一个 class 称为 Packet,两者都是编译的使用 boost 进入 Python 扩展,我想 return 一个指向来自 Packet 模块的 Info 对象的指针。

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);
}

Packet.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>());
}


testPacket.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

有什么方法可以 return 指向 Info 对象的指针吗?

谢谢

您只导入了 Packet.

您还需要导入 Info

否则,如错误所述,当 p.test() 尝试使用它时,Python 无法识别它(或者更具体地说,return 指向它的指针,分配给 t).