【发布时间】:2012-01-23 00:13:25
【问题描述】:
我想我一定在这里遗漏了一些东西,我希望有人能提供帮助。 假设我有一个使用以下构造函数声明的 C++ 类:
class Value {
public:
Value();
Value(const char *val);
void append(const Value &val);
private:
...
};
创建一个简单的 SWIG 接口文件后,类似于:
%module(naturalvar=1) Value
%{
#include "value.h"
%}
%include "value.h"
我可以为 Python 创建包装器代码:
>>> import Value
>>> v1 = Value.Value()
>>> v2 = Value.Value("test")
>>> v1.append(v2)
>>> v1.append(Value.Value("test"))
但我不能这样做:
>>> v1.append("test")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/jakob/dev/test/Value.py in append(self, *args)
298 def resize(self, *args): return _Value.Value_resize(self, *args)
299 def isValidIndex(self, *args): return _Value.Value_isValidIndex(self, *args)
--> 300 def append(self, *args): return _Value.Value_append(self, *args)
301 def get(self, *args): return _Value.Value_get(self, *args)
302 def removeMember(self, *args): return _Value.Value_removeMember(self, *args)
TypeError: in method 'Value_append', argument 2 of type 'Value const &'
显然它知道如何使用 Value(const char *value) 构造函数,但我如何让它理解传递给 append 方法的字符串应该被馈送/转换为 Value 对象。
最好的问候 雅各布·西蒙-加德
【问题讨论】:
-
看起来 Python 不支持隐式转换(或者 SWIG 没有将隐式构造函数转换为隐式转换)
标签: c++ constructor swig