【问题标题】:Getting char array from c dll in python as string从python中的c dll获取char数组作为字符串
【发布时间】:2018-06-04 09:30:03
【问题描述】:

我是 ctypes 的初学者,我不知道如何在 python 中将 char 数组转换为字符串。我已经开始使用了:

create_string_buffer(bytes(var, 'utf8')) 填充一个数组,但没有运气使用“byref()”将其作为字符串返回。

如果有人知道您将成为救生员。提前致谢!

【问题讨论】:

标签: python c ctypes


【解决方案1】:

ctypes 页面:[Python]: ctypes - A foreign function library for Python
不看代码很难判断,但这里有一个例子:

>>> import sys
>>> import ctypes
>>> "Python {:s} on {:s}".format(sys.version, sys.platform)
'Python 3.5.2 (default, Nov 23 2017, 16:37:01) \n[GCC 5.4.0 20160609] on linux'
>>> src = "some dummy Python string"
>>> src_charp = ctypes.create_string_buffer(src.encode())
>>> dst_initial = b"Just "
>>> dst_charp = ctypes.create_string_buffer(len(dst_initial) + len(src) + 1)
>>> dst_charp
<ctypes.c_char_Array_25 object at 0x7fe6c41209d8>
>>> dst_charp.value
b''
>>> for idx, c in enumerate(dst_initial):
...     dst_charp[idx] = c
...
>>> dst_charp.value
b'Just '
>>> ctypes.CDLL(None).strcat(dst_charp, src_charp)
32414128
>>> dst_charp
<ctypes.c_char_Array_25 object at 0x7fe6c41209d8>
>>> dst_charp.value
b'Just some dummy Python string'
>>> dst = dst_charp.value.decode()
>>> dst
'Just some dummy Python string'

注意事项

【讨论】:

  • 解决方案确实很丑陋:cp = create_string_buffer(bytes(" ", 'utf8') ) 然后从函数内部使用byref(cp) 获取它,你得到对象 str(cp.value) 最终返回所需的字符串/路径我没有知道它为什么会起作用,所以如果有人能详细说明一下这种蟒蛇的疯狂,我会很感激。谢谢
  • 所以参数是一个输入输出。我修改了代码以反映这一点。正如我在一开始所说的那样,如果没有任何代码,很难猜测你的情况会发生什么。为了正确理解,调用函数的 Python 代码应该可用,C 函数声明也应该可用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
相关资源
最近更新 更多