Sample Project [Download]
1. 環境設定
注意:x64版本 python 在 linking 時會出問題,建議使用 x86 版本- OS: Windows 8.1
- Visual Studio 2013 Update4
- python-3.3.5.msi (x86)
- swigwin-3.0.2
2. 設定VC的Include, Library, Execute path
Include
Project 右鍵 Properties | Configuration Properties | C/C++- Additional Include Directories: C:\Python33\include
Library
Project 右鍵 Properties | Configuration Properties | Linker- Additional Library Directories: C:\Python33\libs
Executable
Project 右鍵 Properties | Configuration Properties | VC++ Directories- Executable Directories: C:\swigwin-3.0.2
3. 建立C/C++ DLL Project
- New Project...
- Templates > Visual C++ > Win32 > Win32 Console Application
- Project name: Sample
- OK
- Next
- 選擇 DLL, Empty project
- Finish
Project Property | C/C++ | Precompiled Headers | Precompiled Header 切換成 "Not Using Precompiled Headers" |
4. 撰寫C/C++的API - Sample.h, Sample.cpp
Sample.h#include "Python.h" int AddOne(int n); int Sqrt(int n); PyObject* SqrtInPyObj(PyObject* obj);
Sample.cpp
#include "Sample.h" int AddOne(int n) { return n+1; } int Sqrt(int n) { return n*n; } PyObject* SqrtInPyObj(PyObject* obj) { int n = PyLong_AsLong(obj); return Py_BuildValue("i", n*n); }
5. 設置interface檔 - Sample.i
Project 右鍵 Properties | Configuration Properties | Build Events | Pre-Build Eventswig.exe -c++ -python -o $(ProjectDir)\Sample_wrap.cxx $(ProjectDir)Sample.i
Sample.i範例
%module Sample %{ #include "Sample.h" %} %include "Sample.h"
其餘按照參考網址