Python:如何增加ctypes POINTER实例 [英] Python: how to increment a ctypes POINTER instance

查看:616
本文介绍了Python:如何增加ctypes POINTER实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char)).

因此,我们有p.contents.value == "f".

如何直接访问和操纵(例如递增)指针?例如.就像(p + 1).contents.value == "o".

How can I directly access and manipulate (e.g. increment) the pointer? E.g. like (p + 1).contents.value == "o".

推荐答案

您必须使用索引:

>>> p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char))
>>> p[0]
'f'
>>> p[1]
'o'
>>> p[3]
'\x00'

看看ctypes文档了解有关使用指针的更多信息.

Have a look at ctypes documentation to find out more about using pointers.

更新:看来这不是您所需要的.然后,让我们尝试另一种方法:首先将指针转换为void,将其递增,然后将其转换回LP_c_char:

UPDATE: It seems that it's not what you need. Let's, then, try another approach: first cast the pointer to void, increment it and then cast it back to LP_c_char:

In [93]: p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char))

In [94]: void_p = ctypes.cast(p, ctypes.c_voidp).value+1

In [95]: p = ctypes.cast(void_p, ctypes.POINTER(ctypes.c_char))

In [96]: p.contents
Out[96]: c_char('o')

也许它并不优雅,但可以.

Maybe it's not elegant but it works.

这篇关于Python:如何增加ctypes POINTER实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆