Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c++ - std::vector to boost::python::list

I have a method in c++ that gets called from python and needs to return a python list object.

I have already created the method, and its attached to an exposed class and callable from python right now... (it returns void).

So the question is, how do I create a python list from this:

std::vector<std::string> results;

I am not really understanding how the constructor works from this documentation:

http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/list.html

Also... I don't really want to return kind of wrapped vector... I just want to create a new python list with the string values from the vector.

My apologies if this is a duplicate... I found quite a few list to vector questions but I couldn't find any about creating a new python list.

I could expand this question to include some other questions like:

Creating a new python dictionary from a: std::map<std::string, std::string> and so on.

question from:https://stackoverflow.com/questions/6157409/stdvector-to-boostpythonlist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

boost::python already includes functionality for wrapping vectors and maps. Here's sample code for vectors, as you can see both passing and returning lists is quite simple:

// C++ code
typedef std::vector<std::string> MyList;
class MyClass {
  MyList myFuncGet();
  void myFuncSet(const Mylist& list);
  //       stuff
};

// Wrapper code

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

using namespace boost::python;


BOOST_PYTHON_MODULE(mymodule)
{
    class_<MyList>("MyList")
        .def(vector_indexing_suite<MyList>() );

    class_<MyClass>("MyClass")
        .def("myFuncGet", &MyClass::myFuncGet)
        .def("myFuncSet", &MyClass::myFuncSet)
        ;
}

Maps are very similar to vectors and are described in this post: Boost::Python- possible to automatically convert from dict --> std::map?

Unfortunately boost::python does not currently include facilities for wrapping lists. You can create the wrapper manually, but I'm out of time for this answer. I can post it today or tomorrow. I'd appreciate a new question about this particular problem, because the answer will be quite extensive and is probably outside of the scope of this post. I'd just avoid lists and use vectors instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...