简体   繁体   English

获取“没有为 C++ 类注册 Python 类”错误,将 C++ 对象传递给 Python 函数

[英]Getting "No Python class registered for C++ class" error, passing C++ object to Python function

I tried to write a simple embedded python program, following the tutorials and samples I found.我尝试按照我找到的教程和示例编写一个简单的嵌入式 python 程序。 It should simply create a class in C++, pass it to a python function, which calls its only method:它应该简单地在 C++ 中创建一个类,将其传递给一个调用其唯一方法的 python 函数:

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".运行它,我收到以下错误消息:“TypeError:没有为 C++ 类 TestClass 注册 Python 类”。 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.我发现了一个问题,关于通过C ++对象到Python功能,甚至试图逃避解决方案完全相同的代码,但仍然得到了同样的错误。

Any idea what do I miss?知道我想念什么吗?

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将 init 函数附加到 inittab 。

PyImport_AppendInittab("test", PyInit_test);

This should be called before Py_Initialize() .这应该在Py_Initialize()之前Py_Initialize()

Now test is available for import like any other Python module.现在test可以像任何其他 Python 模块一样导入。 You can do it from Python code or from C++:您可以从 Python 代码或 C++ 中执行此操作:

PyImport_ImportModule("test");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM