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

2024-09-24 02:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个C++类,我通过SWIG导出,并且一个函数的数组是^ {< CD1>}s:

typedef class Foo {
  int i;
} Foo;

void func(Foo *all_foos);

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

^{pr2}$

我有一张打印地图不起作用。看我需要帮助的地方。在

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

基本上,我有一个PyObjecto;我需要从中得到SwigPyObject(我是否只是投射它?还是会员?)然后以某种方式从SwigPyObject获取我的Foo指针。在


Tags: 函数inputsizeiffoocheck数组all
3条回答

我会尝试使用carrays.i,类似于

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

void func(Foo *all_foos);

然后在python中:

^{pr2}$

只有当没有其他SWIG工具来实现您想要的API时,才应该使用Typemaps。我认为它甚至有可能比上面的更好,使用%inline(单独的答案,因为与此非常不同)。在

你的例子有点困惑,因为你的C++函数取^ {CD1>},但是你的类型映射要用^ {CD2>}(即FOS与FOS的指针数组)。我假设你指的是后者,因为这是从你给出的函数声明中判断数组有多长的唯一合理方法。在

关于即时问题“如何将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”类型映射将变成:

^{pr2}$

请注意,为了使typemap成为通用的和可重用的,我用special typemap variables替换了它的一部分,生成的代码与我们看到的单个示例相同,但是您可以稍微重用它。在

这已经足够编译和运行您给出的示例代码了(只做了一个修改),但是仍然存在内存泄漏。您调用malloc(),但从不调用free(),因此我们需要添加相应的'freearg' typemap

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

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


作为一般点,因为这是C++,我认为你的接口设计错误了——没有充分的理由不使用^ {CD9>},^ {CD10>}或类似的,这也使得包裹更简单。使用头文件中的typedef也是一种奇怪的风格。在

如果是我写这篇文章,我会在包装器中使用RAII,即使我不能改变接口来使用容器。这意味着我要把我的“输入”类型图写成:

%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库中已经具有良好类型映射的类型,您仍然可以通过使用%rename来“隐藏”默认实现,并使用%pythoncode来插入一些其他具有相同名称的Python,从而为Python用户提供一个直观的Python接口对Python用户透明地将Python输入传递到carrays接口中。在

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

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

这里不需要打印地图。在

相关问题 更多 >