ctypes可以用指针算术吗?python 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;
}
现在你明白我在做什么是创建整数数组,并在参考两个指针保持在结构。一个指针在开始,一个在末尾,而不是保持第一个指针和数组的长度。
现在在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
所以现在的问题。是否可能用ctypes做指针运算?我知道你可以通过索引访问数组的值,但我不想那样,因为我不想在我的结构中引用长度。
为什么?通过这样做你会获得什么? – TemporalWolf
这不是关于为什么,而是如何。这是一个简单的例子来展示我想要的,而不是我所做的。 – Olivier
我不同意......这似乎是[XY问题](https://meta.stackexchange.com/a/66378/344593)给我的。 – TemporalWolf