關鍵字:Python 2.7,VS 2010,swig
OS:Win8.1 with update。
1.下載swig:http://www.swig.org/download.html
2.將swig的路徑添加到環境變量Path,例如set path=C:\swigwin-3.0.2。
3.用VS創建一個win32 console application名為MyApp並生成解決方案,編譯生成MyApp.exe。
4.在MyApp解決方案里面新建一個win32 dll帶導出符號項目名為MyDll,編譯生成MyDll.dll。
5.在MyApp解決方案里面新建一個win32 dll空項目名為MyPython。
6.修改項目依賴關系。MyApp依賴於MyDll,MyPython依賴於MyDll。
7.修改CMyDll類的實現如下:
MyDll.h
#pragma once #include <string> using namespace std; #ifdef MYDLL_EXPORTS #define MYDLL_API __declspec(dllexport) #else #define MYDLL_API __declspec(dllimport) #endif // This class is exported from the MyDll.dll class MYDLL_API CMyDll { public: CMyDll(void); virtual ~CMyDll() {} string SayHello(string name); double add(double i, double j); virtual string location(); };
MyDll.cpp
#include "stdafx.h" #include "MyDll.h" CMyDll::CMyDll() { return; } string CMyDll::SayHello(string name) { return "Hello " + name + ". I'm from " + location() + "."; } double CMyDll::add(double i, double j) { return i + j; } string CMyDll::location() { return "C++"; }
8.在MyPython項目里添加接口文件MyPython.i。
%module(directors="1") MyPython
%{
#include "../MyDll/MyDll.h"
%}
%feature("director") CMyDll;
%include <windows.i>
%include <std_string.i>
%include "../MyDll/MyDll.h"
9.在MyPython.i的屬性設置里面設置Custom Build Tool。
10.編譯MyPython.i生成MyPython.py和MyPython_wrap.cxx,把MyPython_wrap.cxx添加到工程MyPython,並設置工程如下,Build工程MyPython生成_MyPython.pyd.
11.添加TestMyPython.py如下,在_MyPython.pyd的文件夾目錄下運行TestMyPython.py.
import MyPython import os o = MyPython.CMyDll() print(o.SayHello("World")) class MyPyDll(MyPython.CMyDll): def __init__(self): MyPython.CMyDll.__init__(self) def location(self): return "Python" o1 = MyPyDll(); print(o1.SayHello("World")) os.system("pause")
運行結果如下:
Hello World. I'm from C++.
Hello World. I'm from Python.
Press any key to continue . . .
12.Run python in MyApp。
修改MyApp的工程屬性,添加python頭文件的文件夾,和lib文件的文件夾。
修改MyApp.cpp的代碼如下:
#include "stdafx.h" #include <Python.h> int _tmain(int argc, _TCHAR* argv[]) { Py_Initialize(); PyObject * pModule = PyImport_ImportModule("TestMyPython"); Py_Finalize(); return 0; }
編譯運行MyApp.exe,結果如下:
Hello World. I'm from C++.
Hello World. I'm from Python.
Press any key to continue . . .
源代碼下載:https://github.com/ldlchina/CppPythonSwig/tree/839e3e50993d209c83c4b5c587369c98a8f05d5a