使用SWIG包装C/C++供Python使用
有多种方法可以将现有的C或C++功能包装到Python中。在本节中,我们将了解如何使用SWIG包装C/C++功能。以下是其他在python中包装c/c++功能的选项。
- 手动包装
- 使用pyrex包装C代码。
- Ctypes
- SIP
- Boost Python
SWIG(简单的包装器接口生成器)能够使用多种其他语言包装C代码,包括Perl、Python、PHP、Ruby、Tcl、C#、Common Lisp(CLISP、Allegro、CL、UFFI、CFFI)、Java、Modula-3和OCAML。Swig还支持多种解释型和编译型Scheme实现(如Guile、MzScheme、Chicken)。
但这里我们只讨论它与python的实现。
SWIG本质上是一种宏语言,它理解C代码,然后会为选择的语言输出包装代码。
安装
我使用的是“swigwin-3.0.12” windows swig安装程序,您可以从以下地址下载:
http://www.swig.org/download.html
除此之外,您可能需要“Microsoft Visual Studio 14.0”或更高版本才能在Windows上运行swig程序。
为了说明swig的使用,假设我们有一些c函数,我们想将其添加到其他语言中,例如Tcl、Perl、Python(我正在与python交互)、Java和C#。
我的c文件是example.c
#include "example.h"
int fact(int n) {
if (n < 0) { /* This should probably return an error, but this is simpler */
return 0;
}
if (n == 0) {
return 1;
} else {
/* testing for overflow would be a good idea here */
return n * fact(n-1);
}
}接口文件
现在,如果您想将您的c文件添加到您喜欢的语言中,您需要编写一个“接口文件”,它是SWIG的输入。我的example.c的接口文件是:
example.i
/* File: example.i */
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include "example.h"头文件
我们在之前的示例文件中包含了头文件。所以这是我的头文件
example.h
int fact(int n);
设置文件
from distutils.core import setup, Extension
example_module = Extension('_example',
sources=['example_wrap.c', 'example.c'],
)
setup (name = 'example',
version = '0.1',
author = "SWIG Docs",
description = """Simple swig example from docs""",
ext_modules = [example_module],
py_modules = ["example"],
)创建包装器
现在我们将使用我们的接口文件(example.i)创建python包装器。要为您的函数创建包装器,只需在您的CLI上运行以下命令。
>swig -python example.i
现在如果您查看您的当前工作目录,就会发现刚刚创建了一个新文件。如果您使用的是与我相同的文件名,那么您的包装器文件将是“example_wrap.c”,否则包装器文件将被命名为类似
“Your_File_Name” + “_wrapper” + “Your_language_extension”
因此,如果您的示例文件是test.c,那么您的包装器文件将是“test_wrapper.c”。
构建扩展
>python setup.py build_ext running build_ext building '_example' extension creating build creating build\temp.win32-3.6 creating build\temp.win32-3.6\Release ….
就是这样,现在我们能够将我们的c语言包装到python语言中。要检查它,您可以直接运行或创建一个虚拟环境并单独运行。
C:\Users\rajesh>mkdir swigExample && cd swigExample C:\Users\rajesh\swigExample>virtualenv swigenv Using base prefix 'c:\python\python361' New python executable in C:\Users\rajesh\swigExample\swigenv\Scripts\python.exe Installing setuptools, pip, wheel...done. C:\Users\rajesh\swigExample>.\swigenv\Scripts\activate (swigenv) C:\Users\rajesh\swigExample>python
就是这样,现在从您的文件中导入函数并运行它。
>>> from example import fact >>> fact(6) 720
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP