简体   繁体   English

从ctypes的c_char_p中检索字符串

[英]Retrieve the string from ctypes's c_char_p

In Python, I have a ctypes.c_char_p's string, 'Hello, world'. 在Python中,我有一个ctypes.c_char_p的字符串,'Hello,world'。 It seems that python automatically encodes it to a number (see below from my ipython console). 似乎python会自动将其编码为一个数字(请参阅下面的ipython控制台)。 How can I retrieve the string, namely, 'Hello, world', from the ctypes.c_char_p object? 如何从ctypes.c_char_p对象中检索字符串,即“Hello,world”?

In [45]: from ctypes import c_char_p

In [46]: c_char_p("Hello, World")
Out[46]: c_char_p(4508383228)

As already mentioned in comments, although perhaps not as explicitly as some might require, the .value attribute converts from ctypes.c_char_p to a Python string. 正如在注释中已经提到的那样,虽然可能没有某些可能需要的那样明确,但.value属性从ctypes.c_char_p转换为Python字符串。

This code round trips a Python string to a ctypes.c_char_p and then back to a Python string: 此代码将Python字符串ctypes.c_char_pctypes.c_char_p ,然后返回到Python字符串:

>>> p = c_char_p("Hello, World")
>>> p
c_char_p(140323010068388)
>>> type(p)
<class 'ctypes.c_char_p'>
>>> s = p.value
>>> s
'Hello, World'
>>> type(s)
<type 'str'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM