python - 从 DLL 返回的 char[] 转换为 Python 字符串

标签 python c string ctypes

我正在尝试将 C 风格的 const char[] 字符串指针(从 DLL 返回)转换为 Python 兼容的字符串类型。但是当 Python27 执行时:

import ctypes

charPtr = ctypes.cast( "HiThere", ctypes.c_char_p )
print( "charPtr = ", charPtr )

我们得到:charPtr = c_char_p('HiThere')

也许有些事情没有被正确评估。 我的问题是:

  1. 应该如何将这个 charPtr 转换回 Python 兼容的、可打印的字符串?
  2. 刚才提到的cast操作是不是在做它应该做的事情?

最佳答案

ctypes.cast() 用于将一个 ctype 实例转换为另一种 ctype 数据类型。 您不需要将其转换为 python 字符串。 只需使用“.value”在 python 字符串中获取它。

>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> print c_s.value
Hello, World

更多信息 here

关于python - 从 DLL 返回的 char[] 转换为 Python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8875185/

相关文章:

string - Coq 中字符的单引号表示法?

python - 我正在尝试使用 python 将 mp4 文件转换为文本,但出现此错误

python - 在 python 中创建负载配置文件函数

c - ARM 汇编中的递归打印 100

c++ - 导入库如何工作?详情?

c# - 动态 LINQ 日期时间比较字符串构建 - Linq To Entities

python - 在zc.buildout中,如何安装egg A,然后安装egg B,而egg B需要egg A才能正确安装?

python - tensorflow sess.run 返回 List 而不是 float32 导致 TypeError : unsupported operand type(s) for +=: 'float' and 'list'

c - 递增后取消引用指向 volatile int 的指针

java - 用空格分隔每个大写单词