我有一个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;
}
}
基本上,我有一个PyObject
o;我需要从中得到SwigPyObject
(我是否只是投射它?还是会员?)然后以某种方式从SwigPyObject
获取我的Foo
指针。在
我会尝试使用carrays.i,类似于
然后在python中:
^{pr2}$只有当没有其他SWIG工具来实现您想要的API时,才应该使用Typemaps。我认为它甚至有可能比上面的更好,使用%inline(单独的答案,因为与此非常不同)。在
你的例子有点困惑,因为你的C++函数取^ {CD1>},但是你的类型映射要用^ {CD2>}(即FOS与FOS的指针数组)。我假设你指的是后者,因为这是从你给出的函数声明中判断数组有多长的唯一合理方法。在
关于即时问题“如何将Python对象转换为给定类型的C++指针?”我通常通过让SWIG为我生成一些代码然后检查它来解决这个问题。例如,如果您有一个函数
void bar(Foo*);
,那么SWIG将在包装器中生成一些代码:有趣的是对
^{pr2}$SWIG_ConvertPtr
的调用,它正在做你想做的事情。有了这些知识,我们只需要将它放入您已经为您的typemap编写的循环中,那么您的“in”类型映射将变成:请注意,为了使typemap成为通用的和可重用的,我用special typemap variables替换了它的一部分,生成的代码与我们看到的单个示例相同,但是您可以稍微重用它。在
这已经足够编译和运行您给出的示例代码了(只做了一个修改),但是仍然存在内存泄漏。您调用
malloc()
,但从不调用free()
,因此我们需要添加相应的'freearg' typemap:它在成功和错误时都会被调用,但这很好,因为
$1
被初始化为NULL,因此无论我们是否成功malloc
,行为都是正确的。在作为一般点,因为这是C++,我认为你的接口设计错误了——没有充分的理由不使用^ {CD9>},^ {CD10>}或类似的,这也使得包裹更简单。使用头文件中的typedef也是一种奇怪的风格。在
如果是我写这篇文章,我会在包装器中使用RAII,即使我不能改变接口来使用容器。这意味着我要把我的“输入”类型图写成:
这样就消除了对“freearg”类型映射的需要,而且不会泄漏。在
如果出于某种原因,您不想编写自定义类型映射,或者更改接口以使用SWIG库中已经具有良好类型映射的类型,您仍然可以通过使用
%rename
来“隐藏”默认实现,并使用%pythoncode
来插入一些其他具有相同名称的Python,从而为Python用户提供一个直观的Python接口对Python用户透明地将Python输入传递到carrays接口中。在您应该能够使用标准的“前端”刷卡工具完成所有操作:
这里不需要打印地图。在
相关问题 更多 >
编程相关推荐