可以用SWIG来把C++的代码封装成Python库,供Python调用。
1 原始文件
编写好原始的h和cpp文件,示例如下:
//File: Tool.h
int fuc1();
int fuc2();
//File: Tool.cpp
#include <iostream>
using namespace std ;
//File: Tool.cpp
int fuc1()
{
cout<<"test---fuc1"<<endl;
return 0 ;
}
int fuc2()
{
cout<<"test---fuc2"<<endl;
return 0;
}
2 编写.i接口文件
新增加文件Tool.i,内容如下:
//File: Tool.i
%module Tool
%{
#define SWIG_FILE_WITH_INIT
#include "Tool.h"
%}
int fuc1() ;
int fuc2() ;
.i接口文件中主要包含了三个部分:
%module
后面的名字是被封装的模块名称,Python通过这个名称加载程序。%{...%}
之间所添加的内容,一般包含此文件需要的一些函数声明和头文件。- 最后一部分,声明了要封装的函数和变量。
如果把要封装的函数声明部分写在了头