gpt4 book ai didi

python - 如何在Python中访问指针值?

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:37 25 4
gpt4 key购买 nike

我有这个Python指针声明:

numberOfThings = ctypes.c_int32()
indexes = ctypes.c_int32()

如果我打印值:

print numberOfThings.value
print indexes.value

我得到了:

0
0

我进行函数调用:

the_Dll.doSomeThing(ctypes.byref(numberOfThings), ctypes.byref(indexes))

如果我现在打印值:

print "numberOfThings values", numberOfThings.value
print "indexes values", indexes.value

我得到了:

numberOfThings values 3
indexes values 147107816

索引是一个指向指针的指针,但是如何获取索引的值呢?我的目标是循环遍历 numberOfThings 的 nr 并为每个 numberOfThings 打印索引的值,如下所示:

for i in range(numberOfThings.value):
print 'Value of indexes', how to access indexes real value?

有人知道怎么解决这个问题吗?谢谢!

最佳答案

来自Python的official documentation :

Pointer instances are created by calling the pointer() function on a ctypes type:

 >>>
>>> from ctypes import *
>>> i = c_int(42)
>>> pi = pointer(i)
>>>

Pointer instances have a contents attribute which returns the object to which the pointer points, the i object above:

 >>>
>>> pi.contents
c_int(42)
>>>

因此,如果我正确理解了您的问题,您应该:

  1. 使用指针而不是int32类型
  2. 通过 variable.contents 属性访问指针内容(又名取消引用指针)。

更新

跟进我们最后的评论,这里是您可能的解决方案的格式化版本:

numberOfThings = ctypes.c_int32() 
indexes = ctypes.c_void_p()

_Dll.doSomeThing(ctypes.byref(numberOfThings),ctypes.byref(indexes))

ptrt = ctypes.POINTER(ctypes.c_double*numberOfThings.value)
mydblPtr = cast(indexes, ctypes.POINTER(ctypes.c_double*numberOfThings.value))

indexes = ptrt(mydblPtr.contents)

for content in indices.contents:
print content

关于python - 如何在Python中访问指针值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24605464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com