linello
linello

Reputation: 8694

Cython mapping c++ data structures

I'm using cython to wrap my C++ class:

Foo.h

class Foo
{
private:
    std::map<int,int > myMap;
    std::vector<int> myVector;
public:
    // An example of internal structures initialization
    Foo()
    {
        for (int i=0; i<10; i++)
        {
             myVector.push_back(i);
             myMap[i]=i*i;
        }
    }
    std::map<int,int> getMyMap()
    {
        return myMap;
    }
    std::vector<int> getMyVector()
    {
        return myVector;
    }
}

I'm wondering if there is some way to get the std::map as python dict and the std::vector as python list without explicitly creating (and thus wasting memory) copies of such structures.

A temptative implementation for the std::vector is the following:

cdef extern from "Foo.h":
    cdef cppclass Foo:
    Foo()
    vector[int]  getMyVector()


cdef class pyFoo:
cdef Foo *thisptr      # hold a C++ instance which we're wrapping
def __cinit__(self):
    self.thisptr = new Foo()

def getMyVector(self):
    cdef vector[int] aa
    cdef int N
    b= []
    aa = self.thisptr.getMyVector()
    N=aa.size()
    for i in range(N):
        b.append(aa[i])
    return b;

But this clearly must store two structures containing the same data. I'm wondering if there is a way to map from c++ to list with cython or should I use boost::python?

Upvotes: 0

Views: 1629

Answers (1)

iabdalkader
iabdalkader

Reputation: 17312

There's a very good reason to convert the vector to a python list, which is using it as a regular list in python code. However, you can wrap the vector and add a getter function. You will save some memory indeed, but I think that would be much less efficient, as you'll have to call the function each time to get a value and you won't be able to use it in any python expressions as you would a python list.

Upvotes: 1

Related Questions