gpt4 book ai didi

c++ - Cython 映射 c++ 数据结构

转载 作者:行者123 更新时间:2023-11-28 07:54:26 24 4
gpt4 key购买 nike

我正在使用 cython 包装我的 C++ 类:

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;
}
}

我想知道是否有某种方法可以将 std::map 作为 python dict 并将 std::vector 作为 python list 而无需显式创建(并因此浪费内存)此类结构的拷贝。

std::vector 的尝试性实现如下:

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;

但这显然必须存储两个包含相同数据的结构。我想知道是否有一种方法可以从 C++ 映射到 cython 列表,或者我应该使用 boost::python?

最佳答案

有一个很好的理由将 vector 转换为 python 列表,即在 python 代码中将其用作常规列表。但是,您可以包装 vector 并添加一个 getter 函数。您确实会节省一些内存,但我认为效率会低得多,因为您每次都必须调用该函数来获取一个值,并且您将无法像在任何 python 表达式中那样使用它 python 名单。

关于c++ - Cython 映射 c++ 数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13064527/

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