您的示例有点困惑,因为您的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) 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(argp);
}
$1[size] = NULL;
}
else {
// Raise exception
SWIG_exception_fail(SWIG_TypeError, "Expected list in $symname");
}
}
请注意,为了使类型映射具有通用性和可重用性,我将其部分替换为special typemap variables-生成的代码与我们看到的单个示例相同,但是您可以稍微重用它.
足以编译和运行您给出的示例代码(仅作了一项更改),但是仍然存在内存泄漏.您调用了malloc(),但从未调用过free(),因此我们需要添加相应的‘freearg’ typemap:
%typemap(freearg) Foo ** {
free($1);
}
这在成功和错误时都会调用,但这很好,因为$1初始化为NULL,所以无论我们是否成功malloc,该行为都是正确的.
作为一个一般的观点,因为这是C语言,所以我认为您的界面设计错误-没有充分的理由不使用std :: vector,std :: list或类似内容,这也使包装更简单.像在头文件中一样使用typedef也是一种怪异的风格.
如果是我在写这篇文章,即使我无法更改使用容器的接口,我也会在包装器中使用RAII.因此,这意味着我可以将“ in”类型映射写为:
%typemap(in) Foo ** (std::vector 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(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设置为“ hide”来为Python用户提供直观的pythonic接口’默认实现和%pythoncode,以向Python用户透明地将一些其他名称与“输入” Python输入到carrays接口的名称相同的Python注入.