我正在使用 SWIG 生成与我的 C 库的 Python 语言绑定(bind)。我已经成功地构建了绑定(bind)和导出的数据结构,但是在使用该库时我必须克服一些困难。
例如,C 头文件的数据类型和函数原型(prototype)如下:
struct MyStruct
{
/* fields */
}
struct MyStruct * MYSTRUCT_Alloc(void);
void MYSTRUCT_Free(struct MyStruct *);
struct MyStruct * MYSTRUCT_Clone(const struct MyStruct *);
int MYSTRUCT_Func1(const struct MyStruct *, const int);
/* and so on */
在我的 SWIG 接口(interface)文件中,我导出函数和 MyStruct 数据类型。假设我的 python 扩展模块名为 foobar,那么我可以像这样编写 Python 脚本:
#import foobar as fb
# The line below creates a Python class which is a wrapper to MyStruct. HOWEVER I cannot pass this class to a function like MYSTRUCT_Func1 until I have initialized it by calling MYSTRUCT_Alloc ...
ms = fb.MyStruct
# This will fail (throws a Python exception)
# ret = fb.MYSTRUCT_Func1(ms, 123)
# However this works
ms = fb.MYSTRUCT_Alloc()
ret = fb.MYSTRUCT_Func1(ms, 123)
声明一个对象并在使用它之前为其分配一个指针是非常麻烦的(并且容易出错)。有没有更好的方法来使用 SWIG 生成的类?我正在考虑包装更高级别的类(或子类化 SWIG 生成的类)以自动处理对象创建和销毁(以及提供一些明显的成员函数,如 MYSTRUCT_Func1()。
但是,如果我对 SWIG 生成的类进行包装/子类化,那么我不确定是否可以将新类传递给需要指向 C 结构的指针的 C API 函数。我无法直接修改 SWIG 生成的类(或者至少我不应该) - 出于明显的原因。
解决这个问题的最佳方法是什么?一种更Python式的创建/销毁对象的方式,同时能够直接将指针传递给公开的C函数?
最佳答案
您的代码:
ms = fb.MyStruct
# This will fail (throws a Python exception)
# ret = fb.MYSTRUCT_Func1(ms, 123)
仅将类分配给 ms
,而不是类的实例,这就是注释行失败的原因。以下内容应该有效:
ms = fb.MyStruct()
ret = fb.MYSTRUCT_Func1(ms, 123)
关于python - SWIG 将 C 库连接到 Python(SWIG 生成的类使用起来很麻烦),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8044870/