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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM