我想了解为什么以下函数在 python 中不起作用:
#include<boost/python.hpp>
#include<iostream>
#include<string>
void hello(std::string& s) {
std::cout << s << std::endl;
}
BOOST_PYTHON_MODULE(test)
{
boost::python::def("hello", hello);
}
当我将库导入到 python 中时
import test
test.hello('John')
我收到错误:
test.hello(str)
did not match C++ signature:
hello(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > {lvalue})
一切都只适用于“std::string s”,但我想通过引用来引用该对象而不复制它。我注意到任何其他带有引用的函数都会弹出错误,例如整数&.
As kindall https://stackoverflow.com/users/416467/kindall前面提到过,Python 字符串是不可变的。一种解决方案可以是 stl::string 包装器。你的Python端会受到影响,但这是一个简单的解决方案,并且为该接口付出的代价很小
class_<std::string>("StlString")
.def(init<std::string>())
.def_readonly("data", &std::string::data);
请注意,assign运算符,python 到 c++ stl 将由 boost 给出,但你必须公开data成员以访问存储的数据。我为 C++ 对象的外观添加了另一个构造函数。
>>> import test
>>> stlstr = test.StlString()
>>> stlstr
<test.StlString object at 0x7f1f0cda74c8>
>>> stlstr.data
''
>>> stlstr = 'John'
>>> stlstr.data
'John'
>>> initstr = test.StlString('John')
>>> initstr.data
'John'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)