Pybind11算是目前最方便的Python調用C++的工具了, 介紹一下在vs2019上寫Python的擴展的HelloWorld
1. 去下載pybind11
https://github.com/pybind/pybind11/releases/tag/v2.3.0
這個庫只要include就可以了
2. 用vs新建一個空項目
2.1 調整輸出類型為dll, 調整輸出文件名為pyd


2.2 include python和pybind11的頭文件, 我的python使用anaconda的全家桶

2.3 鏈接 python的lib

2.4 linker里添加python的lib

3. 代碼示例:
有兩種定義函數的方法, 一種是直接定義, 另一種比較簡單就是 def("函數名",&函數的引用,"說明")
Pybind非常的簡單, 幾乎就不用修改C++的代碼
#include <pybind11/pybind11.h> namespace py = pybind11; int chufa(int a, int b) { return a / b; } PYBIND11_MODULE(example, m) { m.doc() = "...."; m.def("foo", []() { return "Hello world!"; }); m.def("chufa", &chufa, "just chufa"); }
4. build 得到pyd文件


在python中直接import就可以了...
5. 坑:
1. 要注意編譯出來的是64位還是32位的包, 建議全部在64位下編譯, 否則可能會報錯:
ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there
2. pyd的文件名要和包名一致, 如果輸出的pyd文件名稱不對需要手動改過來, 否則會報錯誤:
ImportError: dynamic module does not define module export function