gpt4 book ai didi

python - 如何公开返回变量 vector 的函数?

转载 作者:行者123 更新时间:2023-11-30 02:37:25 27 4
gpt4 key购买 nike

我正在寻找一个 C++ 模块的小型工作示例,它有一个返回 variant vector 并将其暴露给的方法Python(这似乎是一个古老的问题,可以追溯到 2004 ,但我找不到任何明确的答案)。我读过 thisthis还有更多,但我仍然找不到解决方案。至于documentation它似乎立即向读者抛出大量信息。我想要的是一个微小的工作示例,其中包含一个返回一个微小 vector 的微小方法。这就是我现在拥有的:

#include <boost/variant.hpp>
#include <boost/python.hpp>
#include <vector>

using namespace std;
using namespace boost:python

typedef boost::variant<int> variant;
typedef vector<variant> vector;

class Some{
private:
int idx;
public:
Some(...){ ... } //not important
vector MyMethod(){
return vector{1};
}
};

BOOST_PYTHON_MODULE(some){
class_<vector>("vector").def(vector_indexing_suite<vector, true>());
class_<Some>("Some",
init ... //not important
.def("MyMethod",&Some::MyMethod);
}

如果我注释掉这个方法,我对生成的共享库的编译、链接和使用没有任何问题。但是,如果有这样的方法返回一个 vector ,那么我会得到一大堆错误。我想,我需要做一些额外的步骤,比如打鼓和做一些其他的魔术(或一些数据类型转换等),但我不知 Prop 体是什么步骤。

最佳答案

你应该为 variant 编写 to_python_converter,像这样的东西应该可以工作:

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <Python.h>
#include <vector>
#include <boost/variant.hpp>

typedef boost::variant<int> number;
typedef std::vector<number> vector;

vector function()
{
return vector{1};
}

struct number_to_object : boost::static_visitor<PyObject*>
{
static result_type convert(number const& v)
{
return apply_visitor(number_to_object(), v);
}

template<typename T>
result_type operator () (T const& v) const
{
return boost::python::incref(boost::python::object(v).ptr());
}
};

void init_module() {}

BOOST_PYTHON_MODULE(pyexc_test)
{
using namespace boost::python;

class_<vector>("vector").def(vector_indexing_suite<vector, true>());

to_python_converter<number, number_to_object>();
implicitly_convertible<int, number>();

def("function", function);
def("init_module", init_module);
}

关于python - 如何公开返回变量 vector 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31588794/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com