我正在尝试使用 SWIG 来包装现有的 C 库以在 Python 中使用。我在 Windows XP 上使用 Python 2.7.4 运行 swig 2.0.10。我遇到的问题是,我无法调用一个包装的 C 函数,该函数有一个指向 int 的指针作为参数,该参数是存储函数结果的位置。我已将问题提炼为以下示例代码:
convert.c 中的 C 函数:
#include <stdio.h>
#include "convert.h"
#include <stdlib.h>
int convert(char *s, int *i)
{
*i = atoi(s);
return 0;
}
convert.h中的头文件
#ifndef _convert_h_
#define _convert_h_
int convert(char *, int *);
#endif
convert.i中的swig接口(interface)文件
/* File : convert.i */
%module convert
%{
#include "convert.h"
%}
%include "convert.h"
所有这些都使用 Visual C++ 2010 构建到 .pyd 文件中。构建完成后,我在构建目录中留下两个文件:convert.py 和 _convert.pyd。我在此目录中打开一个命令窗口并启动 python session 并输入以下内容:
Python 2.7.4 (default, Apr 6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> import convert
>>> dir(convert)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '_convert', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic', 'convert']
>>> i = c_int()
>>> i
c_long(0)
>>> convert.convert('1234', byref(i))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: in method 'convert', argument 2 of type 'int *'
为什么我的指针对象被拒绝?我应该做什么才能使这项工作成功?
最佳答案
SWIG
和ctypes
是不同的库,因此您无法将 ctypes 对象直接传递给 SWIG 包装的函数。
在 SWIG 中,%apply
命令可以将类型映射应用于常见参数类型,将其配置为 INPUT
, INOUT
,或OUTPUT
参数。请尝试以下操作:
%module convert
%{
#include "convert.h"
%}
%apply int *OUTPUT {int*};
%include "convert.h"
Python 将不再需要输入参数,并将函数的输出更改为返回值和任何 INOUT
的元组。或OUTPUT
参数:
>>> import convert
>>> convert.convert('123')
[0, 123]
请注意,POD(普通旧数据)类型之外的参数通常需要编写您自己的类型映射。咨询SWIG Documentation了解更多详情。
关于python - 使用 SWIG 用指针参数包装 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18645095/