Python 使用SWIG包装带有指针参数的C函数

Python 使用SWIG包装带有指针参数的C函数,python,swig,Python,Swig,我试图使用SWIG包装一个现有的C库,以便在Python中使用。我在WindowsXP上用Python2.7.4运行Swig2.0.10。我遇到的问题是,我无法调用一个包装好的C函数,该函数将指向int的指针作为参数,而int是存储函数结果的地方。我已将问题提炼为以下示例代码: convert.C中的C函数: #include <stdio.h> #include "convert.h" #include <stdlib.h> int convert(char *s,

我试图使用SWIG包装一个现有的C库,以便在Python中使用。我在WindowsXP上用Python2.7.4运行Swig2.0.10。我遇到的问题是,我无法调用一个包装好的C函数,该函数将指向int的指针作为参数,而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.i中的swig接口文件

/* File : convert.i */
%module convert
%{
#include "convert.h"
%}

%include "convert.h"

所有这些都是用Visual C++ 2010构建到.Pyd文件中的。构建完成后,在构建目录中剩下两个文件:convert.py和_convert.pyd。我在此目录中打开一个命令窗口,启动python会话并输入以下内容:

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 *'
%module convert
%{
#include "convert.h"
%}

%apply int *OUTPUT {int*};
%include "convert.h"
win32上的Python 2.7.4(默认值,2013年4月6日19:54:46)[MSC v.1500 32位(英特尔)] 有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。 >>>从ctypes导入* >>>导入转换 >>>目录(转换) [''内置'''''''''''''''''.'文档''.'文件'.''''.'名称'.'''.'''.'包'.'''.'转换'.''''.'新类''.'对象''.'''''.'''.'交换'.'''.'属性'.'交换'.'''.'报告'.''.'交换'.'.'设置属性'.'''.'非动态转换'.'.] >>>i=c_int() >>>我 库隆(0) >>>convert.convert('1234',byref(i)) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 TypeError:在方法“convert”中,参数2的类型为“int*”
为什么我的指针对象被拒绝?我应该怎么做才能使它工作?

SWIG
ctypes
是不同的库,因此不能将ctypes对象直接传递给SWIG包装函数

在SWIG中,
%apply
命令可以将类型映射应用于常见参数类型,以将它们配置为
输入
输入
输出
参数。请尝试以下操作:

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 *'
%module convert
%{
#include "convert.h"
%}

%apply int *OUTPUT {int*};
%include "convert.h"
Python将不再需要输入参数,并将函数的输出更改为返回值和任何
INOUT
output
参数的元组:

>>> import convert
>>> convert.convert('123')
[0, 123]

请注意,POD(纯旧数据)类型之外的参数通常需要编写自己的类型映射。有关详细信息,请参阅。

请参阅上的SWIG手册部分。