我正在学习 pybind 并遵循本教程 https://pybind11.readthedocs.io/en/stable/installing.html
我的行动
python3.10 -m venv venv
source venv/bin/activate
pip install pybind11
然后我正在创建 example.cpp
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function that adds two numbers");
}
并尝试
g++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
我有一个错误:
Undefined symbols for architecture arm64: "_PyBaseObject_Type", referenced from: pybind11::detail::make_object_base_type(_typeobject*) in example-243936.o
在-undefineddynamic_lookup的帮助下修复了错误
g++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
然后我收到了DLL库example.cpython-39-darwin.so 我正在尝试使用该库
# python
Python 3.10.5 (v3.10.5:f377153967, Jun 6 2022, 12:36:10) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pybind11
>>> import example
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'example'
>>>
如何修复导入错误?
详情
MacOS version 12.2.1
pip list
Package Version
---------- -------
pip 22.0.4
pybind11 2.10.4
setuptools 58.1.0
Python 3.10.5
g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/4.2.1
Apple clang version 13.0.0 (clang-1300.0.27.3)
Target: arm64-apple-darwin21.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
最佳答案
虽然添加 $(python3-config --embed --ldflags)
作为注释可能会有所帮助,但提供嵌入 Python 解释器所需的链接器标志(用作 g++ -O3 -Wall -shared -std=c++11 -undefinedynamic_lookup -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) $(python3-config --embed - -ldflags)
),这无法解释原始错误:
ModuleNotFoundError: No module named 'example'
该错误应该意味着共享库 (example.cpython-39-darwin.so
) 不在 Python 可以找到的目录中。
当您尝试导入 example 时,Python 会在多个位置(例如当前目录以及 PYTHONPATH
环境变量中列出的目录)查找名为 example.py
的文件或example.so
.
因此,请尝试将 example.cpython-39-darwin.so
文件夹添加到您的 PYTHONPATH
中:
export `PYTHONPATH=/path/to/directory:$PYTHONPATH`
关于python - 无法在 macOS 上安装 pybind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76262104/