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?

Bence Nagy
  • 43
  • 5

1 Answers1

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");
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243