ctypes是否可以对指针进行算术运算?
首先,让我告诉您我要在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;
}
Run Code Online (Sandbox Code Playgroud)
现在您了解了我在做什么是创建一个整数数组,并将两个指针保持在结构中。一个指针在开头,一个指针在结尾,而不是保留第一个指针和数组的长度。
现在在Python中,我有一个继承自ctypes.Structure的对象,并且是两个继承自ctypes.POINTER(ctypes.c_short)类型的成员。
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
Run Code Online (Sandbox Code Playgroud)
现在是问题了。是否可以对 ctypes 进行指针运算?我知道您可以通过它的索引访问数组的值,但是我不想要那样,因为我不需要结构中的长度引用。
它是令人费解的,但是它c_short以一个字节偏移量计算一个对象,该对象tab 共享其缓冲区,然后获得一个指向它的指针:
from ctypes import *
class c_Foo(Structure):
_fields_ = [
("Bar", POINTER(c_short)),
("end_Bar", POINTER(c_short))
]
tab = (c_short*3)(1,2,3)
foo = c_Foo()
foo.Bar = tab
foo.end_Bar = pointer(c_short.from_buffer(tab,sizeof(c_short)*2))
print(tab[2])
print(foo.Bar[2])
print(foo.end_Bar[0])
tab[2] = 4
print(tab[2])
print(foo.Bar[2])
print(foo.end_Bar[0])
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)3 3 3 4 4 4