Upload
e8xu
View
209
Download
5
Embed Size (px)
Citation preview
SWIG Hello worldCalling C++ function from Pyhon
2014/12/20
Jacky Liu
• This slide organize instructions from “Falldog的程式戰場 - [Python] Windows底下使用SWIG呼叫C/C++的function” (http://falldog7.blogspot.tw/2013/07/python-swig-c-function.html)
Environment Setting
• OS (Windows 7 also works)Windows 8.1
• CompilerVisual Studio 2013 Update4
• Python (Other version may be incompatible)python-3.3.5.msi (x86) [1]
• SWIG (Unzip and copy swigwin-3.0.2 folder to C:\)swigwin-3.0.2 [2]
[1] http://www.python.org/ftp/python/3.3.5/python-3.3.5.msi[2] http://sourceforge.net/projects/swig/files/swigwin/swigwin-3.0.2/
SWIG Hello world
• Our goal is to call a simple C++ function from python.
int AddOne(int n) { return n + 1; }int Sqrt(int n) { return n*n; }
print(Sample.AddOne(1)) # >>> 2print(Sample.Sqrt(2)) # >>> 4
C++
Python
New project
New projectName=Sample
New project
New project
1. DLL2. Empty project3. Finish
Project setting
• Project setting - Include Python header files
> Right click >
Project setting
• Properties | Configuration Properties | VC++ DirectoriesExecutable Directories: C:\swigwin-3.0.2
Project setting
• Project | Properties | Configuration Properties | C/C++Additional Include Directories: C:\Python33\include
Project setting
• Properties | Configuration Properties | LinkerAdditional Library Directories: C:\Python33\libs
Project setting
• Properties | Configuration Properties | Build Events | Pre-Build Eventswig.exe -c++ -python -o $(ProjectDir)\Sample_wrap.cxx $(ProjectDir)Sample.i
Add file
• Add Sample.h
#include "Python.h"
int AddOne(int n);int Sqrt(int n);PyObject* SqrtInPyObj(PyObject* obj);
Add file
• Add 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);
}
Add file
• Add Sample.i
%module Sample
%{#include "Sample.h" %}
%include "Sample.h"
Generate files
• Build “Release” (F7)Generate • $(ProjectDir)/Release/Sample.dll
• $(ProjectDir)/Sample/Sample.py
• $(ProjectDir)/Sample/Sample_wrap.cxx
• Add Sample_wrap.cxx back to project
Configure Linker output file name$(OutDir)\_$(ProjectName).pyd
Add preprocessor definitions__WIN32__
Generate .pyd file for python
• Build “Release” (F7) againGenerate • $(ProjectDir)/Release/_Sample.pyd
Try it in Python
• Copy• $(ProjectDir)/Release/_Sample.pyd
• $(ProjectDir)/Sample/Sample.py
• To the same folder with your script• Test.py
import Sample
print Sample.AddOne(1) # >>> 2print Sample.Sqrt(2) # >>> 4print Sample.Sqrt(3) # >>> 9print Sample.SqrtInPyObj(2) # >>> 4print Sample.SqrtInPyObj(3) # >>> 9
Reference
• Falldog的程式戰場 - [Python] Windows底下使用SWIG呼叫C/C++的function