python - Boost Python - 用参数包装构造函数
问题描述
我已经设计了一个cpp
共享库,现在我想制作一个Python
包装器来使用它。一切正常,直到有必要更改cpp
库构造函数,在其上添加一个参数。
我想知道如何在包装器中反映这个参数,因为下面的代码不再起作用了。我对代码进行了一些更改,现在就像下面这样。我几乎可以肯定问题出在这一行
py::class_<Wrapper>("Wrapper", py::init<>())
但我不知道如何在这里添加参数。我试过了
py::class_<Wrapper>("Wrapper", py::init<>(const std::string ¶m))
并且
py::class_<Wrapper>("Wrapper", py::init<const std::string ¶m>())
但都失败了。
经过一些评论后编辑,我决定使用(不参考)
py::class_<Wrapper>("Wrapper", py::init<const std::string param>())
但我仍然有同样的错误信息。
包装器.hpp
#include "mycpplib.hpp"
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <boost/python/dict.hpp>
namespace py = boost::python;
namespace np = boost::python::numpy;
class Wrapper
{
public:
// change: inclusion of the new parameter
Wrapper(const std::string ¶m);
py::dict function1();
};
包装器.cpp
#include "wrapper.hpp"
namespace py = boost::python;
namespace np = boost::python::numpy;
// change: inclusion of the new parameter
Wrapper::Wrapper(
const std::string ¶m) {
//do something
}
py::dict
Wrapper::function1() {
//do something
}
BOOST_PYTHON_MODULE(libwrapper)
{
Py_Initialize();
np::initialize();
py::class_<Wrapper>("Wrapper", py::init<const std::string param1>())
.def("_function1", &Wrapper::function1)
;
}
包装器.py
import libwrapper
class Wrapper(libwrapper.Wrapper):
# change: inclusion of the new parameter
def __init__(self, param):
libwrapper.Wrapper.__init__(self, param)
def function1(self):
return self._function1()
错误是:
/path/wrapper.cpp: In function 'void init_module_libwrapper()':
/path/wrapper.cpp:24:69: error: template argument 1 is invalid
py::class_<Wrapper>("Wrapper", py::init<const std::string param1>())
^
解决方案
阅读 boost 文档(https://www.boost.org/doc/libs/1_68_0/libs/python/doc/html/tutorial/tutorial/exposing.html)我发现:
py::class_<Wrapper>("Wrapper", py::init<const std::string param1>())
应该这样写:
py::class_<Wrapper>("Wrapper", py::init<const std::string>())
没有参数名称。只是类型
推荐阅读
- jekyll - Jekyll 中的迭代 JSON 数据文件产生双重输出
- android - Android Studio Kotlin 活动在运行时不显示元素
- typescript - 输入“用户 | undefined' 不可分配给类型 'User'
- ecmascript-6 - undefined 不是 setInterval 附近的函数
- javascript - 如何对角重复 HTML Canvas 模式
- python-3.x - 如何在 Python 中修复 statsmodel.tsa.statespace.SARIMAX
- laravel - 如何访问这个值?
- javascript - 有没有更聪明的方法来编写这个 RegExp?
- java - 如何在 Java 中显示错误对话框?
- java - Android 应用程序在定义字节缓冲区以读取文件时崩溃