c/c++封装成python包

参考网址:https://blog.csdn.net/tiankongtiankong01/article/details/80420033

SWIG (Simplified Wrapper and Interface Generator) 是用来为C和C++程序构造脚本语言接口的软件开发工具。SWIG 实际上是一个编译器,获取C/C++的声明,用一个壳包起来,以便通过其他语言访问这些声明。因此,SWIG 最大的好处就是将脚本语言的开发效率和 C/C++ 的运行效率结合起来。
一:准备源文件
文件1:EncryptTool.h
int EncryptFile(const char *szInputFile, const char *szOutputFile);
int DecryptFile(const char *szInputFile, const char *szOutputFile);
文件2:EncryptTool.cpp   # 属于文件1的引用文件或者说是依赖包,后面动态链接将其封装起来
#include <iostream>
 
using namespace std;

int EncryptFile(const char *szInputFile, const char *szOutputFile)
{
   char str[] = "jiami";
 
   cout << "this is  : " << str << endl;
}

int DecryptFile(const char *szInputFile, const char *szOutputFile)
{
   char str[] = "解密函数";
 
   cout << "我是  : " << str << endl;
}
二:编写接口文件
文件3:EncryptTool.i(接口文件)
%module EncryptTool  (定义模块名)
%{
#define SWIG_FILE_WITH_INIT
#include "EncryptTool.h"  
%}
%include "EncryptTool.h"  # 导入源文件
1.%module后面的名字是被封装的模块名称,Python通过这个名称加载程序。
2.%{...%}之间所添加的内容,一般包含此文件需要的一些函数声明和头文件。
3.最后一部分,声明了要封装的函数和变量。
三:封装代码
swig -python -c++ EncryptTool.i

四:生成动态链接库 setup.py文件
from distutils.core import setup, Extension

#生成一个扩展模块
pht_module = Extension('_EncryptTool', #swig模块引用的模块名称,必须要有下划线
                        sources=['EncryptTool_wrap.cxx', #封装后的接口文件
                                 'EncryptTool.cpp',  #原始代码所依赖的文件
                                ],
                      )

setup(name = 'EncryptTool',    #打包后的名称,也是我们python导包的名字
        version = '0.1',  # 版本号
        author = 'SWIG Docs',  # 封装作者
        description = 'Simple swig pht from docs',  # 描述信息
        ext_modules = [pht_module], #与上面的扩展模块名称一致
        py_modules = ['EncryptTool'], #需要打包的模块列表
    )

五:安装到我们的python环境中
安装python3环境中:sudo python3 setup.py install
安装python2环境中:sudo python setup.py install

猜你喜欢

转载自www.cnblogs.com/888888CN/p/12028744.html