【发布时间】:2016-12-13 22:20:51
【问题描述】:
我已经开始使用 SWIG,以便可以在 Python 中使用 C 库。我有这段代码,我将 Python 字符串传递给需要“void *”的 C 函数
example.h:
char test(void *buf);
example.c:
char test(void *buf) {
char *c = (char*)buf;
return *c;
}
Python:
import example
buf = "hello"
example.test(buf)
当我运行它时,我得到以下错误:
TypeError: in method 'test', argument 1 of type 'void *'
但是,当我将“void*”参数更改为“char*”时,它似乎可以工作。我有点困惑,因为我认为“void*”匹配任何类型的指针。无论如何,我四处挖掘并发现了 ctypes 库并将其转换为 c_void_p (Python: converting strings for use with ctypes.c_void_p())。那似乎对我不起作用。
作为一种解决方法,我在我的 swig 文件中做了一个包装器:
/* File: example.i */
%module example
%include typemaps.i
%{
#include "example.h"
%}
%include "example.h"
%inline %{
char test_wrapper(char *buf) {
void *voidBuf = (void*)buf;
return test(voidBuf);
}
%}
这似乎有效。但是,我想知道是否有人可以解释为什么 ctypes 方法不起作用。如果我对 ctypes 方法完全不满意,有没有比创建内联包装器更合适的方法?
谢谢大家!
【问题讨论】:
标签: python-2.7 swig