使用Boost.Python教程示例代码遇ArgumentError,求解决提示
Boost.Python 示例代码参数不匹配错误的解决提示
我最近跟着Boost.Python官方教程写了一段示例代码,运行时却碰到了参数不匹配的错误,折腾半天没搞定,来请教下大家。具体情况如下:
我的C++代码
#include <boost/python.hpp> using namespace boost::python; struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string msg; }; BOOST_PYTHON_MODULE(hello) { class_<World>("World") .def("greet", &World::greet) .def("set", &World::set) ; }
Python终端操作步骤
>>> import hello >>> planet = hello.World() >>> planet.set('howdy')
出现的错误信息
Traceback (most recent call last): File "<stdin>", line 1, in <module> Boost.Python.ArgumentError: Python argument types in World.set(World, str) did not match C++ signature: set(World {lvalue}, std::string)
问题分析与解决方法
这个错误看起来是Python的str和C的std::string类型匹配不上,但其实最可能的原因是**C代码里没包含<string>头文件**!
虽然我们用了std::string,但boost/python.hpp并不会自动包含标准库的<string>头文件。如果没有显式包含,编译器可能无法正确生成std::string的完整类型信息,导致Boost.Python无法完成Python字符串到C++std::string的自动转换。
解决起来很简单:
- 在C++代码开头添加
#include <string>,修改后的代码开头应该是:
#include <string> #include <boost/python.hpp> using namespace boost::python;
另外,也可以检查下编译命令是否正确,确保你链接了对应的Boost.Python库,比如针对Python3的编译命令大概是:
g++ -shared -fPIC -o hello.so hello.cpp -lboost_python3
(具体库名可能根据你的Boost版本和系统有所不同,比如boost_python38对应Python3.8)
修改后重新编译,再运行Python代码应该就能正常工作了!
内容的提问来源于stack exchange,提问作者yanglong
相关产品推荐
相关产品推荐

