python - 使用 SWIG 用指针参数包装 C 函数

标签 python ctypes swig

我正在尝试使用 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 *'

为什么我的指针对象被拒绝?我应该做什么才能使这项工作成功?

最佳答案

SWIGctypes是不同的库,因此您无法将 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/

相关文章:

Python Pandas - 检查子字符串包含并将新列设置为子字符串

Python:ctypes + C malloc 错误。 C内存问题还是Python/ctypes问题?

Perl 5 : namespace issues when `use` ing SWIG-generated module in declared package

c++ - $stdin 与 std::istream 的兼容性,使用 swig、C++ 和 Ruby

Java 和 SDL_GetKeyState()

python - 添加用于 ReportLab 的字体

python - 单个Python脚本的Azure函数部署以及Azure Functions中requirements.txt的安装过程

Python 分布式计算(有效)

python - 如何为 MS Windows PACKAGE_ID 和 PACKAGE_INFO 结构创建 Python ctypes 结构?

python - 如何在 Python 中使用 ctypes 卸载 DLL?