如何在SWIG / Python中将结构列表传递给C语言

时间:2014-02-07 21:04:55

标签: python swig

我有一个我通过swig导出的C ++类,以及一个带有Foo s数组的函数:

typedef class Foo {
  int i;
} Foo;

void func(Foo *all_foos);

现在我希望能够将包含这些内容的python列表传递给all_foos:

afoo = mymod.Foo()
bfoo = mymod.Foo()
mymod.func([afoo, bfoo])

我有一个不起作用的typemap。请参阅FIXME专线,了解我需要帮助的地方。

%typemap(in) Foo ** {
  /* Check if it's a list */
  if (PyList_Check($input)) {
    int size = PyList_Size($input);
    int i = 0;
    $1 = (Foo **) malloc((size+1)*sizeof(Foo *));
    for (i = 0; i < size; i++) {
      PyObject *o = PyList_GetItem($input,i);
      // here o->ob_type->tp_name is "Foo"; could check that
      // FIXME: HOW DO I GO FROM o -> SwigPyObject -> Foo *?  THIS IS WRONG
      $1[i] = (Foo *)(reinterpret_cast<SwigPyObject *>(o))->ptr;
    }
  } else {
    PyErr_SetString(PyExc_TypeError,"not a list");
    return NULL;
  }
}

基本上,我有PyObject o;我需要从中获取SwigPyObject(我刚刚投出它吗?或者它是成员?)然后以某种方式从Foo获取SwigPyObject指针。

3 个答案:

答案 0 :(得分:3)

您的示例有点困惑,因为您的C ++函数需要Foo*,但您的类型映射需要Foo**(即Foos数组与指向Foos的指针数组)。我假设你的意思是后者,因为这是从你给出的函数声明中判断数组有多长的唯一理智的方法。

就直接问题而言“如何将Python对象转换为给定类型的C ++指针?”我通常让SWIG为我生成一些代码然后检查它来解决这个问题。例如,如果你有一个函数void bar(Foo*);,那么SWIG将在包装器中生成一些代码:

SWIGINTERN PyObject *_wrap_bar(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
  PyObject *resultobj = 0;
  Foo *arg1 = (Foo *) 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject * obj0 = 0 ;

  if (!PyArg_ParseTuple(args,(char *)"O:bar",&obj0)) SWIG_fail;
  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Foo, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "bar" "', argument " "1"" of type '" "Foo *""'");
  }
  arg1 = reinterpret_cast< Foo * >(argp1);
  bar(arg1);
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}

有趣的是调用SWIG_ConvertPtr来做你想做的事。有了这些知识,我们只需要将它放在你已经为你的typemap编写的循环中,这样你的'in'类型映射就变成了:

%typemap(in) Foo ** {
  $1 = NULL;
  if (PyList_Check($input)) {
    const size_t size = PyList_Size($input);
    $1 = (Foo**)malloc((size+1) * sizeof(Foo*));
    for (int i = 0; i < size; ++i) {
      void *argp = 0 ;
      const int res = SWIG_ConvertPtr(PyList_GetItem($input, i), &argp, $*1_descriptor, 0);
      if (!SWIG_IsOK(res)) {
        SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " "$argnum"" of type '" "$1_type""'");
      }
      $1[i] = reinterpret_cast<Foo*>(argp);
    }
    $1[size] = NULL;
  }
  else {
    // Raise exception
    SWIG_exception_fail(SWIG_TypeError, "Expected list in $symname");
  }
}

请注意,为了使typemap具有通用性和可重用性,我已用special typemap variables替换了它的部分内容 - 生成的代码与我们看到的单个示例相同,但您可以稍微重复使用它。

这足以编译和运行您给出的示例代码(如上所述进行了一次更改),但仍然存在内存泄漏。您拨打malloc(),但从不free(),因此我们需要添加相应的'freearg' typemap

%typemap(freearg) Foo ** {
  free($1);
}

这在成功和错误时都被调用,但这很好,因为$1被初始化为NULL,所以无论我们是否成功malloc,行为都是正确的。


作为一般性的一点,因为这是C ++我认为你的界面设计错误 - 没有充分的理由不使用std::vectorstd::list或类似的东西也使包装更简单。在头文件中使用typedef也是一种奇怪的风格。

如果是我写这篇文章,我会在包装器中使用RAII,即使我无法更改接口以使用容器。所以这意味着我将'in'字体图写为:

%typemap(in) Foo ** (std::vector<Foo*> temp) {
  if (PyList_Check($input)) {
    const size_t size = PyList_Size($input);
    temp.resize(size+1);
    for (int i = 0; i < size; ++i) {
      void *argp = 0 ;
      const int res = SWIG_ConvertPtr(PyList_GetItem($input, i), &argp, $*1_descriptor, 0);
      if (!SWIG_IsOK(res)) {
        SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " "$argnum"" of type '" "$1_type""'");
      }
      temp[i] = reinterpret_cast<Foo*>(argp);
    }
    temp[size] = NULL;
    $1 = &temp[0]; // Always valid since we +1
  }
  else {
    // Raise exception
    SWIG_exception_fail(SWIG_TypeError, "Expected list in $symname");
  }
}

然后消除了对'freearg'类型映射的需求并且永远不会泄漏。


如果由于某种原因您不想编写自定义类型映射,或者更改界面以使用SWIG库中已有良好类型映射的类型,您仍然可以使用{{为您的Python用户提供直观的pythonic界面1}}'隐藏'默认实现,%rename注入一些额外的Python,其名称与Python用户透明地“压缩”到carrays接口中。

答案 1 :(得分:1)

您应该能够使用标准的“前端”SWIG工具完成所有工作:

%include <std_list.i>

%ignore func
%rename(func) funcWrap

namespace std {
   %template(FooList) std::list<Foo*>;
}

%include "Foo.h"

%inline %{
    // wrap with const list of non-const Foo*
    void funcWrap(const std::list<Foo *>& all_foos)
    {
         // create Foo* array: 
         Foo* fooArray = new Foo(all_foos.size());
         int count = 0;
         for (std::list<Foo *>::const_iterator ii=all_foos.begin(); ...) 
              fooArray[count] = *ii;
         func(fooArray);
         delete fooArray;
    }
%}

这里不应该有typemap。

答案 2 :(得分:0)

我会尝试使用carrays.i,例如

%include carrays.i
%array_class(Foo, FooArray)

void func(Foo *all_foos);

然后在python:

fooArray = FooArray(10)
func(fooArray)

只有在没有其他SWIG工具来实现所需的API时才应使用输入映射。我认为甚至可能比上面做的更好,使用%inline(单独的答案因为与此截然不同)。