gpt4 book ai didi

python - 痛饮 C++/Python : inheritance proxy objects

转载 作者:行者123 更新时间:2023-11-30 02:43:37 26 4
gpt4 key购买 nike

我在 C++ 文件中有类似的东西,它们组成了我的 SWIG 模块:

class CObject {
public:
void do() {
// some treatments
}
};
class Interface {
public:
void add(CObject* obj) {
obj->do();
}
};

在使用我的 SWIG 模块的 python 代码中,有类似的东西:

from mySwigModule import Interface, CObject

class MyObj(CObject):
def __init__(self):
super(CObject, self).__init__()


inter = Interface()
inter.add(MyObj()) // ERROR

这段代码非常基础。真正的处理更大的对象。但问题是:当运行 Python 代码时,会打印类似这样的内容:

NotImplementedError: Wrong number or type of arguments for overloaded function 'Interface_add'.
Possible C/C++ prototypes are:
Interface::add(CObject *)

我如何向 SWIG 解释如何将对象转换为 CObject ?

肯定与类型映射有关,但我不知 Prop 体是什么。我试图在接口(interface)文件中添加它,但没有成功:

 %typemap(in) CObject * {
if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) {
$1 = (CObject *) $1;
}
}

编译时返回的错误类似于:

 error: macro "SWIG_ConvertPtr" requires 4 arguments, but only 3 given
In function ‘PyObject* _wrap_Interface_add__SWIG_0(PyObject*, PyObject*)’:
error: ‘SWIG_ConvertPtr’ was not declared in this scope

在实际代码中,调用 Interface::add() 有 2 个参数。也许类型映射需要指定其他参数的类型?

debian、python 3.2、SWIG 2。

编辑:真正的错误是显示。

最佳答案

您的 __init__ 有错误。试试这个:

def __init__(self):
super(MyObj, self).__init__()

甚至这样:

def __init__(self):
super().__init__()

完成测试:

/* example.i */
%module example
%inline %{
class CObject { public: void do_it() {} };
class Interface { public: void add(CObject* obj) {obj->do_it();} };
%}
# test.py
from example import Interface, CObject

class MyObj(CObject):
def __init__(self): super(MyObj, self).__init__()

Interface().add(MyObj())
$ # build and test procedure
$ swig -o example_wrap.cc -python -c++ example.i
$ g++ -o example_wrap.os -c -fPIC -I/usr/include/python3.4 example_wrap.cc
$ g++ -o _example.so -shared example_wrap.os
$ python3 test.py
$

关于python - 痛饮 C++/Python : inheritance proxy objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25962662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com