I have a float pointer p from a C++ library which I want to increment in a Python module. When I try to write p + distance, I'm receiving the error that the operator + would be undefined for LP_c_float.
A possible solution is to use advance(p, distance) instead, where
def advance(pointer, distance, type = ctypes.c_float):
return ctypes.cast(ctypes.cast(pointer, ctypes.c_voidp).value + distance, ctypes.POINTER(type))
However, is the cast to ctypes.c_voidp really necessary? Why addition is not defined for LP_c_float (or why doesn't it have a similar value field)?
There isn't a direct way to increment a pointer, just the value that the pointer points to. You can use simple indexing to get the next values as shown below.
Assuming you have a
float*to the first element of an array of data,pbelow is the equivalent:Output:
To actually increment the pointer itself you have to jump through hoops. Below increments the pointer by one element, e.g. in C:
p += 1.Output:
As you can see this is expensive. Do the pointer math in C instead if you have to.