SWIG和C ++构造函数

时间:2012-01-23 00:13:26

标签: c++ constructor swig

我想我必须在这里遗漏一些东西,我希望有人可以提供帮助。 假设我有一个用以下构造函数声明的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对象。

祝你好运 雅各布西蒙 - 加尔德

1 个答案:

答案 0 :(得分:1)

Python不会查看赋予函数的参数类型,以确定要调用的函数(忽略方法调度)。所以我认为你不能让python做你想做的事。另一方面,当意识到超载时Swig可以帮助你。如果你重载append()也可以得到你想要的东西。

class Value {
public:
  Value() { }
  Value(const char *val) { }
  void append(const Value &val) { }
  void append(const char *val) { }
};

可能还有另一种更简洁的解决方案,但这似乎对我有用。