1
我有一個擁有一個C++向量成員持有自定義類對象的類。我希望能夠從python中讀取這個向量作爲列表,但我無法以任何方式做到這一點。不能使自定義ctypedef類的cython向量公開
我的頭:
from __future__ import division
import cython
from libcpp.vector cimport vector #this import the C++ vector, which
#is compatible with python lists
import numpy as np
cimport numpy as np
#@cython.boundscheck(False) #this line remove some correct checking for
#for bounds, which makes it hard to debug
#but also faster
這裏是我的自定義類:
ctypedef class boid:
"""Placeholder for the boids"""
cdef public vector[double] pos #position of the boid
cdef public vector[double] vel #velocity of the boid
def __init__(self, vector[double] pos_):
self.pos = pos_
這是其他類,具有矢量。
cdef class csopsim:
"""This is the simulation"""
#declaring c variable types
cdef vector[boid] boids #list of boids
def __init__(self,int scenario):
#setting default values
self.BOX_SIZE = 640
self.BOX = float(self.BOX_SIZE)
self.NUM_MALES = 10
for x in xrange(self.NUM_MALES):
self.boids.push_back(boid(0,np.random.uniform(350,450,2)))
這很好編譯,但顯然試圖讓csopsim.boids拋出一個沒有屬性錯誤。如果我將其修改爲
cdef public vector[boid] boids
它不能編譯。如果我創建一個方法
def getboids(self):
return self.boids
它不編譯。如果我創建一個方法
cdef vector[boid] getboids(self):
return self.boids
它編譯,但是當我試圖從Python中調用該方法,它拋出一個AttributeError:「csopsim.csopsim」對象有沒有屬性「getboids」。我希望有一個簡單而平凡的解決方案來解決這個問題:)
習慣於共享自己的代碼解決方案: - | –