您的示例有点混乱,因为您的 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<Foo*>(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<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 库中已经具有良好类型映射的类型,您仍然可以使用 @987654337 为 Python 用户提供直观的 Pythonic 界面@“隐藏”默认实现,%pythoncode 注入一些额外的 Python,其名称相同,将 Python 输入“按摩”到对 Python 用户透明的 carrays 接口中。