nanobind中__init__函数参数类型不兼容问题求助
解决nanobind中__init__参数类型不兼容的问题
你的问题源于两个细节疏漏:缺少std::string的类型转换支持头文件,以及C++类定义的语法错误,以下是具体修复方案:
1. 引入nanobind的string类型转换头文件
nanobind对C++标准库类型的自动转换需要单独引入对应头文件,std::string与Python str的映射支持在<nanobind/stl/string.h>中,需添加该包含语句:
#include <iostream> #include <nanobind/nanobind.h> #include <nanobind/stl/string.h> // 新增此行
2. 修复C++类定义的语法错误
你的class T定义末尾缺少分号,会导致编译报错,需补上:
class T { public: T(std::string s) { std::cout << "hello world" << std::endl; }; }; // 补上末尾分号
完整修复后的代码
#include <iostream> #include <nanobind/nanobind.h> #include <nanobind/stl/string.h> class T { public: T(std::string s) { std::cout << "hello world" << std::endl; }; }; NB_MODULE(basic_example, m) { nb::class_<T>(m, "T") .def(nb::init<std::string>()) ; }
Python端正确调用方式
编译生成扩展模块后,直接传入Python字符串即可实例化:
import basic_example t = basic_example.T("test_string")
错误提示中出现std::__cxx11::basic_string是因为nanobind未加载string类型转换逻辑,导致直接暴露了C++底层的字符串类型,而非映射为Python的str类型,添加对应头文件后即可自动完成双向类型转换。
内容的提问来源于stack exchange,提问作者got here
相关产品推荐
相关产品推荐

