更新
我不打算添加这个作为答案,因为我还没有在技术上解决这个问题。但是由于我现在已经花了 2.5 天的时间来尝试使用 boost-python3 进行工作,我已经失去了忍受它的意愿。
我刚刚遇到pybind11(我之前对 python 绑定工具的冗长搜索如何没有发现它,我不知道)并且正在使用它。2.5 天的痛苦与 <20 分钟安装和构建他们的cmake 示例相比......所有特定的 python-version-dependency-hell 都消失了。
它在语法上与 boost-python 相似,但更易于管理、更快、仅包含标题并且功能更丰富。
夏天!
原始问题
我正在使用 boost::python 在 python 3.7.2 中绑定一个类。
类导入成功但实例化它会出现以下错误:
<my-terminal>$ python
Python 3.7.2 (default, Feb 14 2019, 17:36:47)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import classes
>>> t = classes.World()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() should return None, not 'NoneType'
>>>
这是classes.cpp:
#include <boost/python.hpp>
#include <boost/python/list.hpp>
#include <boost/python/extract.hpp>
#include <string>
#include <sstream>
#include <vector>
struct World
{
void set(std::string msg) { mMsg = msg; }
void many(boost::python::list msgs) {
long l = len(msgs);
std::stringstream ss;
for (long i = 0; i<l; ++i) {
if (i>0) ss << ", ";
std::string s = boost::python::extract<std::string>(msgs[i]);
ss << s;
}
mMsg = ss.str();
}
std::string greet() { return mMsg; }
std::string mMsg;
};
using namespace boost::python;
BOOST_PYTHON_MODULE(classes)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
.def("many", &World::many)
;
};
月关宝盒
撒科打诨
皈依舞
相关分类