简体   繁体   English

Boost :: Python,将元组转换为Python工作,矢量 <tuple> 才不是

[英]Boost::Python, converting tuple to Python works, vector<tuple> does not

I've been using Boost::Python for a while, and everything always turned out ok. 我已经使用Boost :: Python了一段时间,而且一切都很好。 However yesterday I was trying to find out why a particular type I thought I had registered (a tuple) was giving me errors when I was trying to access it from Python. 然而昨天我试图找出为什么我认为我注册的特定类型(一个元组)在我尝试从Python访问它时给了我错误。

Turns out that while the tuple was actually registered, when trying to access it through an std::vector wrapped via the vector_indexing_suite this is not enough anymore. 事实证明,虽然元组实际上已经注册,但是当试图通过vector_indexing_suite包裹的std::vector访问它时,这已经不够了。

I was wondering, why is it not working? 我在想,为什么它不起作用? Is there any way to make this work? 有没有办法让这项工作? Should I try to wrap the vector by hand? 我应该尝试用手包裹矢量吗?

Below is my MVE: 以下是我的MVE:

#include <tuple>
#include <vector>

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

template <typename T>
struct TupleToPython {
    TupleToPython() {
        boost::python::to_python_converter<T, TupleToPython<T>>();
    }

    template<int...>
    struct sequence {};

    template<int N, int... S>
    struct generator : generator<N-1, N-1, S...> { };

    template<int... S>
    struct generator<0, S...> {
        using type = sequence<S...>;
    };

    template <int... I>
    static boost::python::tuple boostConvertImpl(const T& t, sequence<I...>) {
        return boost::python::make_tuple(std::get<I>(t)...);
    }

    template <typename... Args>
    static boost::python::tuple boostConvert(const std::tuple<Args...> & t) {
        return boostConvertImpl(t, typename generator<sizeof...(Args)>::type());
    }

    static PyObject* convert(const T& t) {
        return boost::python::incref(boostConvert(t).ptr());
    }
};

using MyTuple = std::tuple<int>;
using Tuples = std::vector<MyTuple>;

MyTuple makeMyTuple() {
    return MyTuple();
}

Tuples makeTuples() {
    return Tuples{MyTuple()};
}

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

    TupleToPython<MyTuple>();
    def("makeMyTuple", makeMyTuple);

    class_<std::vector<MyTuple>>{"Tuples"}
        .def(vector_indexing_suite<std::vector<MyTuple>>());
    def("makeTuples", makeTuples);
}

Accessing the resulting .so via Python results in: 通过Python访问生成的.so导致:

>>> print makeMyTuple()
(0,)
>>> print makeTuples()[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: No Python class registered for C++ class std::tuple<int>
>>> 

EDIT: I've realized that the error does not happen if the vector_indexing_suite is used with the NoProxy parameter set to true. 编辑:我已经意识到如果将vector_indexing_suiteNoProxy参数设置为true一起使用,则不会发生错误。 However, I'd prefer if this wasn't necessary, as it makes the exported classes unintuitive in Python. 但是,我更喜欢这不是必需的,因为它使导出的类在Python中不直观。

TupleToPython registers C++-to-Python converters and Python-to-C++ converters. TupleToPython注册了C ++-to-Python转换器和Python-to-C ++转换器。 This is fine. 这可以。

On the other hand, you want your vector elements to be returned by reference. 另一方面,您希望通过引用返回向量元素。 But there's nothing on the Python side that can serve as a reference to your tuple. 但是Python方面没有任何东西可以作为你的元组的参考。 A converted-to-Python tuple may hold the same values, but it is completely detached from the original C++ tuple. 转换为Python的元组可以保存相同的值,但它与原始的C ++元组完全分离。

It looks like in order to export a tuple by reference, one would need to create an indexing suite for it, rather than to/from-Python converters. 看起来为了通过引用导出元组,需要为它创建一个索引套件,而不是为/ from-Python转换器。 I have never done that and cannot guarantee it will work. 我从来没有这样做过,也不能保证它会起作用。

Here's how one could expose a tuple as a minimal tuple-like Python object (with only len() and indexing). 以下是如何将元组公开为最小元组的Python对象(仅使用len()和索引)。 First define some helper functions: 首先定义一些辅助函数:

template <typename A>
int tuple_length(const A&)
{
    return std::tuple_size<A>::value;
}

template <int cidx, typename ... A>
typename std::enable_if<cidx >= sizeof...(A), boost::python::object>::type
get_tuple_item_(const std::tuple<A...>& a, int idx, void* = nullptr)
{
    throw std::out_of_range{"Ur outta range buddy"};
}

template <int cidx, typename ... A, typename = std::enable_if<(cidx < sizeof ...(A))>>
typename std::enable_if<cidx < sizeof...(A), boost::python::object>::type
get_tuple_item_(const std::tuple<A...>& a, int idx, int = 42)
{
    if (idx == cidx)
        return boost::python::object{std::get<cidx>(a)};
    else
        return get_tuple_item_<cidx+1>(a, idx);
};

template <typename A>
boost::python::object get_tuple_item(const A& a, int index)
{
    return get_tuple_item_<0>(a, index);
}

Then expose specific tuples: 然后暴露特定的元组:

using T1 = std::tuple<int, double, std::string>;
using T2 = std::tuple<std::string, int>;

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

    class_<T1>("T1", init<int, double, std::string>())
      .def("__len__", &tuple_length<T1>)
      .def("__getitem__", &get_tuple_item<T1>);

    class_<T2>("T2", init<std::string, int>())
      .def("__len__", &tuple_length<T2>)
      .def("__getitem__", &get_tuple_item<T2>);
}

Note these quasi-tuples, unlike real Python tuples, are mutable (via C++). 请注意,与真正的Python元组不同,这些准元组是可变的(通过C ++)。 Because of tuple immutability, exporting via converters and NoProxy looks like a viable alternative to this. 由于元组不变性,通过转换器和NoProxy输出看起来像是一种可行的替代方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM