用pip安装好pybind11 文件清单,都写在一个目录里
//文件名: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]) #文件名: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))
注意替换setup.py中相关库的位置
在命令行执行 python setup.py build_ext --inplace标签:functions,python,double,in1,c++,dll,extern,in2,cpp From: https://www.cnblogs.com/szyicol/p/18324822
编译好之后会有一个pyd文件
然后测试test.py即可
另外,也可以直接在 vs中写好相关cpp的文件,配置好目录,然后生成dll,改成pyd即可。