我正在包装一个包含结构的 C 库:
struct SCIP
{
//...
}
和创建这样一个结构的函数:
void SCIPcreate(SCIP** s)
SWIG 从中生成一个 python 类 SCIP
和一个函数 SCIPcreate(*args)
。
当我现在尝试在 python 中调用 SCIPcreate()
时,它显然需要一个 SCIP**
类型的参数,我应该如何创建这样的东西?
或者我应该尝试使用自动调用 SCIPcreate()
的构造函数来扩展 SCIP
类吗?如果是这样,我该怎么做?
最佳答案
给定头文件:
struct SCIP {};
void SCIPcreate(struct SCIP **s) {
*s = malloc(sizeof **s);
}
我们可以使用以下方法包装这个函数:
%module test
%{
#include "test.h"
%}
%typemap(in,numinputs=0) struct SCIP **s (struct SCIP *temp) {
$1 = &temp;
}
%typemap(argout) struct SCIP **s {
%set_output(SWIG_NewPointerObj(SWIG_as_voidptr(*$1), $*1_descriptor, SWIG_POINTER_OWN));
}
%include "test.h"
这是两个类型映射,一个创建本地临时指针用作函数的输入,另一个在调用后将指针的值复制到返回中。
作为替代方案,您还可以使用 %inline
设置重载:
%newobject SCIPcreate;
%inline %{
struct SCIP *SCIPcreate() {
struct SICP *temp;
SCIPcreate(&temp);
return temp;
}
%}
关于python - SWIG Python - 包装一个需要双指针指向结构的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13380982/