1

Okay, maybe I'm not finding an answer because I'm not sure how to word it, but I have a class called Info and another class called Packet, both are compiled into Python extensions using boost, and I would like to return a pointer to an Info object from the Packet module.

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()

error message:

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

Is there any way I can return a pointer to an Info object?

Thanks

2
  • Don't you need to import Info too? It says right there it isn't registered... I don't know this technology well, though. Commented Jul 7, 2020 at 21:05
  • hey that worked, I thought all I needed was to import it in the .cpp and link them toghether in the makefile... thanks! Commented Jul 7, 2020 at 21:08

1 Answer 1

2

You only imported Packet.

You also need to import Info.

Otherwise, as the error says, Python doesn't recognise it when p.test() attempts to use it (or, more specifically, to return a pointer to it, to assign to t).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.