Is it possible with ctypes to make pointer arithmetic?
First, let me show you what I'm trying to do in C
#include <stdio.h>
struct Foo {
short *Bar;
short *end_Bar;
};
int main() {
short tab[3] = {1,2,3};
struct Foo foo;
foo.Bar = tab;
foo.end_Bar = foo.Bar + 2; // Pointer arithmetic
short *temp = foo.Bar;
while(temp != foo.end_Bar)
printf("%hi", *(temp++));
printf("%hi", *(foo.end_Bar));
return 0;
}
Now you understand that what I'm doing is creating an array of integer, and keeping in reference two pointers in a structure. One pointer at the begining and one at the end, instead of keeping the first pointer and the length of the array.
Now in Python I have an object that inherit from ctypes.Structure and as two members which are ctypes.POINTER(ctypes.c_short) type.
import ctypes
class c_Foo(ctypes.Structure):
_fields_ = [
("Bar", ctypes.POINTER(ctypes.c_short)),
("end_Bar", ctypes.POINTER(ctypes.c_short))
]
if __name__ == "__main__":
tab = [1,2,3]
foo = c_Foo()
foo.Bar = (c_short * len(tab))(*tab)
foo.end_Bar = foo.Bar + 2 # TypeError, unsupported operand
So now the question. Is it possible to do pointer arithmetic with ctypes? I know that you can access value of the array by it index, but I don't want that, because I don't want a length reference in my structure.
c_shortautomatically converts the indexed value to a Python integer. This behavior is disabled for subclasses of simple types, since it's assumed that you need to preserve the derived type. So if use a subclass ofc_short, then you could usectypes.pointer(foo.Bar[2]). There are other options, but it gets increasingly cumbersome.