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