SWIG 封装C++接口给Python调用

什么是SWIG

SWIG is a software development tool that connects programs written in
C and C++ with a variety of high-level programming languages. SWIG is
used with different types of target languages including common
scripting languages such as Javascript, Perl, PHP, Python, Tcl and
Ruby. The list of supported languages also includes non-scripting
languages such as C#, D, Go language, Java including Android, Lua,
OCaml, Octave, Scilab and R. Also several interpreted and compiled
Scheme implementations (Guile, MzScheme/Racket) are supported. SWIG is
most commonly used to create high-level interpreted or compiled
programming environments, user interfaces, and as a tool for testing
and prototyping C/C++ software. SWIG is typically used to parse C/C++
interfaces and generate the ‘glue code’ required for the above target
languages to call into the C/C++ code. SWIG can also export its parse
tree in the form of XML. SWIG is free software and the code that SWIG
generates is compatible with both commercial and non-commercial
projects.

简单来说SWIG就是 各种编程语言的 转换器,可以将C++代码编译给Python调用。

下载

SWIG官网下载:https://sourceforge.net/projects/swig/files/swigwin

外网下载较慢,我这里有较新的一个windows版本 swigwin-4.0.1.zip

链接:https://pan.baidu.com/s/1tIe8S2Yr_R3qSzFI9hb9Xw 提取码:zeei

添加系统环境变量

下载完之后解压缩到一个地方,copy文件夹地址,比如我的是 D:\App\swigwin-4.0.1
控制面板>编辑系统环境变量,可以直接点击键盘 Win 键搜索 关键字 “环境变量
在这里插入图片描述
用户变量 > Path > 新增 D:\App\swigwin-4.0.1

使用C++封装

编写封装说明文件

swig封装需要一个.i后缀文件的封装说明,其中

  • %module name 为封装名称,Python调用的包名就是 name
  • %{…%} 为附加的函数说明和头文件,源文件以外的部分都要包括在这里,包括头文件和宏定义等
    之后为要封装的函数或类,可以直接引用头文件(若已经将要封装的部分的声明写在头文件中)
%module Example_swig
%{
#include "example.h"
%}

%include "example.h"

调用swig封装

在命令行中输入swig -python -c++ <swig_config>.i,其中<swig_config>.i为上面写的说明文件

swig -python -c++ example.i

调用后生成两个文件:

  • name_wrap.cxx文件
  • name.py文件
  • 我们把这里的c/c++文件叫做low-level,生成的py叫做high-level,对于c/c++的生成文件需要进行编译并链接其余的部分(文件中所引用的东西)创建一个扩展module,对于py文件,就是要导入的文件。
  • 说下名字的问题。比如我们用的module:test.i就会默认生成一个加了_wrap的包装器test_wrap.c。如果要更改的话,可以使用swig的可选项-o指定。生成的py文件就是同名的.py文件。

使用VS编译

1. 新建动态链接库项目

文件 > 新建 > 项目
在这里插入图片描述

2. 配置输出类型

生成 > 配置管理器 中设置:

  • 活动解决方案配置为Release
  • 活动解决方案平台为X64(本机为64位机)

在这里插入图片描述

3. 添加Python 库
  • 项目>属性 中配置Python的库

  • 在VC++目录中的 包含目录 中,导入Python安装路径下的include路径(包含Python.h)
    比如我的是 C:\Apps\anaconda3.6\include

  • 链接器 > 常规 的附加库目录中,导入Python安装路径下的libs路径(注意不是Lib路径,包括dll文件)
    比如我的是 C:\Apps\anaconda3.6\libs

  • 将之前生成的 name_wrap.cxx 添加到工程源文件中
    源文件 > 添加 > 现有项
    在这里插入图片描述

  • 最后点击确定
    在这里插入图片描述

编译输出

  • 选择 生成 > 生成解决方案,在X64->Release文件夹下有一个dll文件,即为编译输出的动态链接库。
  • 将其名称改为**_name.pyd**(本例中为**_ZQGL2.pyd**),将其与swig生成的name.py文件放在同一目录中

调用测试

import ...

参考

Windows平台下Python使用swig调用C++
swig 实践(python & c/c++)(一)

发布了66 篇原创文章 · 获赞 81 · 访问量 58万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章