【问题标题】:casting into a Python string from a char[] returned by a DLL从 DLL 返回的 char[] 转换为 Python 字符串
【发布时间】:2012-01-16 02:26:06
【问题描述】:

我正在尝试将 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. 刚才提到的强制转换操作是否在做它应该做的事情?

【问题讨论】:

    标签: python c string ctypes


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      如果您设置 ctypes 函数的 argtypesrestype 属性,它们将返回正确的 Python 对象,而无需强制转换。

      这是一个调用 C 运行时 timectime 函数的示例:

      >>> from ctypes import *
      >>> m=CDLL('msvcrt')
      >>> t=c_long(0)
      >>> m.time(byref(t))
      1326700130
      >>> m.ctime(byref(t))  # restype not set
      6952984
      >>> m.ctime.restype=c_char_p  # set restype correctly
      >>> m.ctime(byref(t))
      'Sun Jan 15 23:48:50 2012\n'
      

      【讨论】:

      • @HelinWang 不,它没有。在这种情况下,ctime 返回一个指向静态内存的指针,因此无需管理任何内容。
      • 一般情况你知道吗? : c 库返回了在堆上分配的内存。
      • @HelinWang 即使在一般情况下,如果 C 分配它,C 必须释放它。在这种情况下,您也不想使用 c_char_p,因为 ctypes 是“有用的”并将其转换为 Python 字符串。您没有得到返回的指针,因此无法将其传递给 ctypes 包装的 free 函数。使用另一种类型,例如POINTER(char)c_void_p,提取字符串,然后将指针传递给free 等。
      猜你喜欢
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      相关资源
      最近更新 更多