一、什麼是swigpython
SWIG 是一個很是優秀的開源工具,支持您將 C/C++
代碼與任何主流腳本語言相集成。此外,它向更普遍的受衆公開了基本代碼,改善了可測試性,讓您的 Ruby 代碼庫某部分能快速寫出高性能的 C/C++
模塊。
c++
二、SWIG安裝app
到官網下載swigwin文件包,解壓到一個文件夾中;工具
解壓的文件夾中有個swig.exe文件,把該文件的路徑添加到系統路徑Path中;性能
設置一下python路徑,好讓解壓的swig文件夾中的example例子跑起來。測試
官網上的描述:ui
三、使用SWIG封裝spa
以swigwin-3.0.7\Examples\python\class爲例子,通常C++有兩個文件,一個頭文件,一個程序文件。rest
第一步:須要新建一個後綴爲i的文件,文件內容是這樣的code
=================================================================================================
/* File : example.i */
%module example 用來指定模塊名字
%{
#include "example.h" 這個大括號裏面一般是放置是的被封裝的文件能編譯所須要的頭文件和一些聲明等。
%}
/* Let's just grab the original header file here */
%include "example.h" 須要暴露給用戶的一些接口、類什麼的,能夠直接把頭文件放在這,把裏面的東西全暴露
=====================================================================================================
第二步:利用swig將原文件依據目標語言的特性作一個轉換,轉換後一般生產一個XXXXXX_wrap.cxx,一個XXXXXX.py
The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of
your C/C++ application to create an extension module. The Python source file contains high-level support code
轉換就是在文件所在的目錄環境下輸入:
swig -c++ -python example.i
第三步:即然都說了要編譯,那就編譯吧,將轉換後的文件編譯下。編譯的方法有三種,一種是Using distutils,另外一種是Hand compiling a dynamic module,還有一個是Static linking。後兩種沒研究。
在目錄下新建setup.py
===========================
#!/usr/bin/env python
"""
setup.py file for SWIG example
"""
from distutils.core import setup, Extension
example_module = Extension('_example',
sources=['example_wrap.cxx', 'example.cxx'],
)
setup (name = 'example',
version = '0.1',
author = "SWIG Docs",
description = """Simple swig example from docs""",
ext_modules = [example_module],
py_modules = ["example"],
)
==========================================
而後敲:python setup.py build_ext --inplace
若是報錯: Unable to find vcvarsall.bat
直接:
在「..python安裝路徑...\Lib\distutils目錄下有個msvc9compiler.py找到243行
toolskey = "VS%0.f0COMNTOOLS" % version 直接改成 toolskey = "VS你的版本COMNTOOLS"
2010的就是 toolskey = "VS100COMNTOOLS"