带有C ++重载函数的SWIG类型映射

时间:2013-01-08 16:57:11

标签: c++ overloading swig

我有一个像这样的函数定义:

void Foo(int szData,int Data []);

我有一个像这样的SWIG类型图:

%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;
}

typemap允许我从Python调用Foo(),如下所示: FOO((1,2,3))

这非常有效,直到我添加一个重载函数,例如: int Foo(double t);

一切都很好,但现在当我从Python调用Foo()时,我得到了:

NotImplementedError: Wrong number or type of arguments for overloaded function 'Foo'.
  Possible C/C++ prototypes are:
    Foo(int,int [])
    Foo(double)

如果我删除了typemap(in),那么它也能正常工作。

感谢任何人有任何想法,因为我完全被难过......

2 个答案:

答案 0 :(得分:5)

重命名SWIG接口文件中的typemapped函数。 SWIG确实支持多态,但它在将元组与C类型匹配时存在问题。这是我的界面:

%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进行构建和测试:

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 :(得分:1)

扩展Mark Tolonen的答案。

您可以添加到您的 UPDATE [s] SET [strcol] = NULL WHERE NOT EXISTS ( SELECT [strcol] FROM [other] WHERE [s].[strcol] = [other].[strcol]) 文件中:

demo.i

您会得到名称不变的多态性