类中的自类型对象-TypeError:未找到C ++类型的to_python(按值)转换器

时间:2019-03-30 14:23:18

标签: c++ python-2.7 visual-studio boost-python

我正在尝试使用boost.python公开具有2个成员(val和parent)的类(Child)。两者都是公共的,并且父类型为Child。编译没有错误,但是当我尝试访问父级时,我的python包装器带来了以下内容:

TypeError: No to_python (by-value) converter found for C++ type: class

我对C ++,python和boost.python非常陌生。我可能会遗漏一些很明显的东西,但是我不太明白这里出了什么问题。

我正在Windows 7上使用Visual Studio Community 2017和python2.7(均为64位)。

以下是不同的代码段:

Child.h

class Child {
public:
    Child();
    double val;
    Child* parent;
};

Child.cpp

#include "Child.h"

Child::Child()
{
    val = 0.0;
}

Wrapper.cpp

#include <boost/python.hpp>
#include "Child.h"

BOOST_PYTHON_MODULE(WrapPyCpp)
{
    boost::python::class_<Child>("Child")
        .def_readwrite("val", &Child::val)
        .def_readwrite("parent", &Child::parent)
        ;
}

Wrapper.py

import WrapPyCpp

class_test = WrapPyCpp.Child()
class_test.val = 1.0

class_test_parent = WrapPyCpp.Child()
class_test.parent = class_test_parent

print class_test_parent.val
print dir(class_test)
print class_test.val
print class_test.parent.val

当我启动Wrapper.py时,最后一行抛出异常:

C:\Users\Visual Studio 2017\Projects\MinExBoostPython2\x64\Debug>Wrapper.py
0.0
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__instance_size__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'parent', 'val']
1.0
Traceback (most recent call last):
  File "C:\Users\Visual Studio 2017\Projects\MinExBoostPython2\x64\Debug\
Wrapper.py", line 12, in <module>
    print class_test.parent.val
TypeError: No to_python (by-value) converter found for C++ type: class Child * __ptr64

C:\Users\Visual Studio 2017\Projects\MinExBoostPython2\x64\Debug>

我希望访问父级及其成员val。 据我所了解的错误,我想象我如何暴露被声明为指针的parent。我说得对吗?

我使用.def_readwrite("parent", &Child::parent)是因为它是Child的公开成员,但我不确定这是访问它的正确方法。

我试图在boost.python文档中找到信息,并查看了

TypeError: No to_python (by-value) converter found for C++ type

Boost.Python call by reference : TypeError: No to_python (by-value) converter found for C++ type:

但是如果我的问题的解决方案在那里,那么我就不会明白。

无论如何,如果有人可以帮助我改正错误并向我解释为什么我错了,我将不胜感激!

谢谢!

1 个答案:

答案 0 :(得分:0)

编辑

我发现了,替换了行

boost::python::class_<Child>("Child")

通过

boost::python::class_<Child, Child*>("Child")

Wrapper.cpp中的

解决了我的问题。结果就是预期的:

C:\Users\Visual Studio 2017\Projects\MinExBoostPython2\x64\Debug>Wrapper.py
0.0
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__instance_size__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'parent', 'val']
1.0
0.0

C:\Users\Visual Studio 2017\Projects\MinExBoostPython2\x64\Debug>

希望它对某人有帮助!