SWIG typemap with C++ overloaded function
我有一个这样的函数定义:
void foo(int szdata,int data[]);
我有一个这样的Swig类型图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | %typemap(in) (int szData,int Data[]) { int i; if (!PyTuple_Check($input)) { PyErr_SetString(PyExc_TypeError,"Expecting a tuple for this parameter"); $1 = 0; } else $1 = PyTuple_Size($input); $2 = (int *) malloc(($1+1)*sizeof(int)); for (i =0; i < $1; i++) { PyObject *o = PyTuple_GetItem($input,i); if (!PyInt_Check(o)) { free ($2); PyErr_SetString(PyExc_ValueError,"Expecting a tuple of integers"); return NULL; } $2[i] = PyInt_AsLong(o); } $2[i] = 0; } |
类型映射允许我从python调用foo(),如下所示:foo((1,2,3))
直到我添加一个重载函数,比如:int foo(双t);
一切都构建良好,但现在当我从python调用foo()时,我得到:
1 2 3 4 | NotImplementedError: Wrong number or type of arguments for overloaded function 'Foo'. Possible C/C++ prototypes are: Foo(int,int []) Foo(double) |
号
如果我把打字图(中)去掉,它也能正常工作。
如果有人有任何想法,我会很感激,因为我完全被难住了…
重命名swig接口文件中的typemapped函数。Swig确实支持多态性,但它在将元组与C类型匹配时遇到问题。这是我的界面:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | %module demo %begin %{ #pragma warning(disable:4127 4100 4211 4706) %} %{ #include <iostream> void Foo(int size, int data[]) { std::cout << __FUNCSIG__ << std::endl; } void Foo(double d) { std::cout << __FUNCSIG__ << std::endl; } void Foo(int a,int b) { std::cout << __FUNCSIG__ << std::endl; } void Foo(int a) { std::cout << __FUNCSIG__ << std::endl; } %} %typemap(in) (int szData,int Data[]) { int i; if (!PyTuple_Check($input)) { PyErr_SetString(PyExc_TypeError,"Expecting a tuple for this parameter"); $1 = 0; } else $1 = (int)PyTuple_Size($input); $2 = (int *) malloc(($1+1)*sizeof(int)); for (i =0; i < $1; i++) { PyObject *o = PyTuple_GetItem($input,i); if (!PyInt_Check(o)) { free ($2); PyErr_SetString(PyExc_ValueError,"Expecting a tuple of integers"); return NULL; } $2[i] = PyInt_AsLong(o); } $2[i] = 0; } void Foo(int a, int b); void Foo(double d); void Foo(int a); %rename Foo Foot; void Foo(int szData,int Data[]); |
我的Visual Studio 2012生成和测试:
1 2 3 4 5 6 7 8 9 10 11 | C:\Demo>swig -c++ -python demo.i && cl /nologo /LD /W4 /EHsc demo_wrap.cxx /Fe_demo.pyd /Ic:\python33\include -link /LIBPATH:c:\python33\libs && python -i demo.py demo_wrap.cxx Creating library _demo.lib and object _demo.exp >>> Foo(1) void __cdecl Foo(int) >>> Foo(1,1) void __cdecl Foo(int,int) >>> Foo(1.5) void __cdecl Foo(double) >>> Foot((1,2,3)) void __cdecl Foo(int,int []) |
号
从马克·托隆那里扩展答案。
您可以添加到您的
1 2 3 4 5 6 7 8 | %insert("python") %{ FooOld = Foo def Foo(arg): if (isinstance(arg,tuple)): return Foot(arg) else: return FooOld(arg) %} |
你得到了名称不变的多态性