現有若干用C++編寫的函數,爲了可以用Python調用它們,能夠經過pybind11將它們封裝到一個Python模塊中,在編寫Python程序時只要導入該模塊便能使用這些函數。python
//文件名:add.cpp extern "C" double add(double in1, double in2) { return in1 + in2; }
//文件名:sub.cpp extern "C" double sub(double in1, double in2) { return in1 - in2; }
//文件名:mul.cpp extern "C" double mul(double in1, double in2) { return in1 * in2; }
//文件名:div.cpp extern "C" double div1(double in1, double in2) { return in1 / in2; }
//文件名:functions.h #ifndef FUNCTIONS_H #define FUNCTIONS_H #include <iostream> using namespace std; extern "C" double add(double, double); extern "C" double sub(double, double); extern "C" double mul(double, double); extern "C" double div1(double, double); #endif
//文件名:functions_wrapper.cpp #include <pybind11/pybind11.h> #include "functions.h" namespace py = pybind11; PYBIND11_MODULE(functions, m){ m.doc() = "Simple Class"; m.def("add", &add); m.def("sub", &sub); m.def("mul", &mul); m.def("div", &div1); }
#文件名:setup.py from setuptools import setup, Extension functions_module = Extension( name = 'functions', sources = ['add.cpp', 'sub.cpp', 'mul.cpp', 'div.cpp', 'functions_wrapper.cpp'], include_dirs = [r'D:\software\pybind11-master\include', r'D:\software\Anaconda\include'] ) setup(ext_modules = [functions_module])
在命令行執行python setup.py build_ext --inplace
,在當前路徑下生成pyd動態庫。
ios
#文件名:test.py import functions print(functions.add(0.9, 3)) print(functions.sub(0.9, 3)) print(functions.mul(0.9, 3)) print(functions.div(0.9, 3))
output:
3.9
-2.1
2.7
0.3
app