使用pybind11传递float16 ndarray到C++时出现未定义符号错误
解决pybind11传递float16 ndarray时的未定义符号错误
这个错误源于C++标准库ABI不匹配或编译选项未正确启用C++20标准,解码后的符号属于std::__cxx11命名空间的std::string内部函数,以下是具体解决步骤:
1. 确保编译时启用C++20标准
std::float16_t是C++20新增的类型,GCC 13需要显式指定编译标准才能正常识别。
直接使用g++编译
执行以下命令:
g++ -O3 -Wall -shared -std=c++20 -fPIC $(python3 -m pybind11 --includes) check_dtype.cpp -o check_dtype$(python3-config --extension-suffix)
使用setup.py编译
修改setup.py文件,添加C++20编译参数:
from setuptools import setup, Extension import pybind11 ext_modules = [ Extension( "check_dtype", ["check_dtype.cpp"], extra_compile_args=["-std=c++20"], include_dirs=pybind11.get_include(), ), ] setup( name="check_dtype", ext_modules=ext_modules, cmdclass={"build_ext": pybind11.setup_helpers.build_ext}, )
2. 强制统一C++ ABI(可选)
Ubuntu 22.04默认使用__cxx11 ABI,但如果环境存在旧编译产物冲突,可在编译命令中显式添加宏定义:
# 在g++命令中追加 -D_GLIBCXX_USE_CXX11_ABI=1
3. 替换为兼容类型规避std::float16_t问题(可选)
若上述方案仍无效,可避开std::float16_t的兼容性限制,直接用uint16_t接收NumPy float16的内存数据(NumPy float16本质是16位二进制存储):
修改C++代码:
#include <iostream> #include <cstdint> #include <pybind11/pybind11.h> #include <pybind11/numpy.h> namespace py = pybind11; void check_array(py::array_t<std::uint16_t> arr) { auto r = arr.unchecked<1>(); for (ssize_t i = 0; i < r.shape(0); ++i) { std::cout << "Element " << i << " has a size of " << sizeof(r(i)) << " bytes." << std::endl; } } PYBIND11_MODULE(check_dtype, m) { m.def("check_array", &check_array, "A function to check the byte size of array elements."); }
编译完成后运行Python代码,即可正常输出每个元素的字节大小为2字节。
内容的提问来源于stack exchange,提问作者lzn
相关产品推荐
相关产品推荐

