swig是一种可以将C++代码转换为多种脚本语言封装的工具,可以在swig官网www.swig.org下载,解压后将swig.exe的路径添加到环境变量path中即可使用swig
编写需要在Python中调用的C++代码,最好将函数和类的声明统一放到头文件中,函数和类的实现放到源文件中
头文件主要包括:
#include
调用(例如#include <iostream>
)using namespace std;
#include <iostream>
using namespace std;
class example {
private:
int num;
public:
void say_hello(void);
void change(int din);
int get_num();
};
源文件为头文件中函数和类的实现
#include "example.h"
void example::say_hello(void) {
cout << "hello python,I am C++" << endl;
}
void example::change(int din) {
num = din;
}
int example::get_num(void) {
return num;
}
swig封装需要一个.i
后缀文件的封装说明,其中
%module <name>
为封装名称,Python调用的包名就是<name>
%{...%}
为附加的函数说明和头文件,源文件以外的部分都要包括在这里,包括头文件和宏定义等%module Example_swig
%{
#include "example.h"
%}
%include "example.h"
在命令行中输入swig -python -c++ <swig_config>.i
,其中<swig_config>.i
为上面写的说明文件
swig -python -c++ example.i
调用后生成两个文件:
python3.5使用的编译器是VC140编译器,对应版本是VS2015,本次使用的是VS2017使用VC141编译器。需要在VS2017中安装VC140编辑器,可以直接在工具->获取工具和功能
中安装
在C++的空工程基础上建立环境
在生成->配置管理器
中设置:
活动解决方案配置
为Release
活动解决方案平台
为X64
(本机为64位机)配置输出
在项目->属性
中配置Python的库
VC++目录
中的包含目录
中,导入Python安装路径下的include路径(包含Python.h)链接器->常规
的附加库目录
中,导入Python安装路径下的libs路径(注意不是Lib路径,包括dll文件)配置头文件
配置库
选择生成->生成解决方案
,在X64->Release文件夹下有一个dll文件,即为编译输出的动态链接库。将其名称改为_<name>.pyd
(本例中为_Example_swig.pyd
),将其与swig生成的<name>.py
文件放在同一目录中
在python,使用import <name>
即可调用刚才生成的包(同一目录下)
import Example_swig
a = Example_swig.example()
a.say_hello()
a.change(3)
print(a.get_num())
hello python,I am C++
3
[Finished in 0.2s]