类中的self类型的对象 - TypeError:找不到C ++类型的to_python(by-value)转换器

问题描述 投票:0回答:1

我试图使用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。到目前为止,我理解错误,我想我有一个问题,我如何暴露父被声明为指针。我对么?

我使用.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:

但如果我的问题的解决方案在那里,我没有得到它。

无论如何,如果有人能帮我纠正错误并解释我为什么错了,我将非常感激!

谢谢!

c++ python-2.7 visual-studio boost-python
1个回答
0
投票

Edit

我想通了,换了线

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>

希望它可以帮到某人!

© www.soinside.com 2019 - 2024. All rights reserved.