0

I tried to write a simple embedded python program, following the tutorials and samples I found. It should simply create a class in C++, pass it to a python function, which calls its only method:

class TestClass
{
public:
    void f() { std::cout << "Hello world!" << std::endl; }
};

typedef boost::shared_ptr<TestClass> tc_ptr;

BOOST_PYTHON_MODULE(test)
{
   boost::python::class_<TestClass>("TestClass")
       .def("f", &TestClass::f);
}

int main()
{
    Py_Initialize();
    PyRun_SimpleString(
        "def g(tc):\n"
        "    tc.f()\n");
    tc_ptr test_class(new TestClass);
    boost::python::object p_main = boost::python::object(
                                       boost::python::handle<>(
                                           boost::python::borrowed(PyImport_AddModule("__main__"))));
    boost::python::object func = p_main.attr("g");
    func(boost::python::ptr(p.get()));

    Py_Finalize();
    return 0;
}

Running it, I get the following error message: "TypeError: No Python class registered for C++ class TestClass". I found a question about passing C++ objects to python functions, even tried to run the exact same code from the solution, but still got the same error.

Any idea what do I miss?

2
  • You need to initialize your test module. Simply declaring it doesn't work. Commented Sep 30, 2020 at 21:15
  • Thank you, it solved it! If you add this as an answer I will mark it as the solution. Commented Oct 1, 2020 at 11:49

1 Answer 1

1

You need to initialise your test module. Simply declaring it doesn't work.

The best way to do it is to append the init function to the inittab with PyImport_AppendInittab.

PyImport_AppendInittab("test", PyInit_test);

This should be called before Py_Initialize().

Now test is available for import like any other Python module. You can do it from Python code or from C++:

PyImport_ImportModule("test");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.