python ctypes指针算法

标签 python ctypes

是否可以使用 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 进行指针运算?我知道您可以通过索引访问数组的值,但我不想那样,因为我不想在我的结构中使用长度引用

最佳答案

这很复杂,但它会在共享其缓冲区的 tab 中的字节偏移处计算一个 c_short 对象,然后获取指向它的指针:

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])
3
3
3
4
4
4

关于python ctypes指针算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685080/

相关文章:

Python IDLE 如何从编辑器进入 shell

python - 为什么 2019 年我们仍然不能使用 ctypes 从 Python 调用 C++?

python - 如果索引不同,如何停止在 Pandas 中移动列

python - 如何在 Mac 的终端中运行 python?

python - 通过 python ctypes 调用带有 char* 参数的 C 函数 python2 和 python3 的区别

python 使用 CDLL 加载 c lib,在 python 路径中看不到库

python - ctypes内存管理: how and when free the allocated resources?

python - 子类化 ctypes - Python

Python3 turtle 将代码保存到文件

python - 当我在 pycharm 中运行 '' 'sns.histplot(df ['price' ] )'' ' 时,我得到代码输出,但没有图表,这是为什么?