I have a C++ class with a variable that is a dynamic array. It is extremely simple, currently only for testing purposes:
class testClass {
public:
int *x;
testClass();
~testClass();
};
The variable x
is initialised with some values, currently through the constructor. I am trying to write a python wrapper code for the C++ class through Cython that can access x
. How can I do this?
Best thing would be to be able to access the variable without copying a lot of data, as x
might be large. Can I access it as a numpy array?
Example, that it behave as numpy array, that could be read only for instance? I want to be able to use the data in x
in other calculations with python, so a numpy array is preferred.
I suppose I could make a GET
method that initialize a numpy array, passes it it to the GET
method and populate it with the data from x
with a loop, but this would copy the data, and does not seem very elegant. Hoping for a better solution.
I have tried with a static array, and found a solution that sort of worked. If x
is static, I could do the following in a .pyx
file:
cdef extern from "testClass.h":
cdef cppclass testClass:
testClass()
int x[5]
cdef class pyTestClass:
cdef testClass *thisptr
def __cinit__(self):
self.thisptr = new testClass()
def __dealloc__(self):
del self.thisptr
property x:
def __get__(self):
return self.thisptr.x
If I access x
in Python, I will get a Python list with the values back.
How to access dynamic C++ array variable, belonging to an object, with Python?
Have a look at this example that explains how to expose arrays allocated in C to numpy without data copies. The relevant line to create, for instance, a 1D numpy array of integers in Cython with already allocated data is,
ndarray = np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT, data_pointer)
See the corresponding Numpy documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.