当我们为分配的值调用 SWIG_ConvertFunctionPtr 时,我从 Swig 生成的 setter 函数中收到错误,指出预期类型不正确。为了简单起见,让我们考虑 (void*) 函数指针。
C代码:
typedef void (*MyFunctionPtr)();
struct MyStruct {
MyFunctionPtr func;
};
Python代码:
import example
def my_python_function():
print("Hello from Python!")
my_struct = example.MyStruct()
my_struct.func = my_python_function
分配会引发运行时错误。除了包含头文件之外,我没有在 swig 代码中添加任何内容来处理这个问题。 我无法从文档或其他论坛中找到任何技巧。 我无法修改 C 代码,因此通过 python/swig 寻找解决方案。
您对我如何解决这个问题有什么想法吗?任何指示都会非常有帮助。
编辑(实验):
经验1: typemap 将输入类型转换为 void 指针(但由于类型不匹配仍然出现相同的错误)
%typemap(in) void* MyFunctionPtr %{
PyObject *func;
if (PyCallable_Check($input)) {
func = $input;
} else {
PyErr_SetString(PyExc_TypeError, "funcptr must be a callable object");
return NULL;
}
$1 = (void*)func;
%}
经验2:
我在 swig 中遇到了以下 C 回调技巧。但在这种情况下,他们将 python 函数作为 PyObject 传递,然后在函数参数中将其类型转换为 void。
http://www.fifi.org/doc/swig-examples/python/callback/widget.i
在这种情况下仍然无法实现结构分配。
部分解决方案: