简体   繁体   English

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

[英]casting into a Python string from a char[] returned by a DLL

I am attempting to cast a C style const char[] string pointer (returned from a DLL) into a Python compatible string type. 我试图将C样式const char []字符串指针(从DLL返回)转换为Python兼容的字符串类型。 but when Python27 executes: 但是当Python27执行时:

import ctypes

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

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

perhaps something is not to be evaluating properly. 也许某些事情无法正确评估。 My questions are: 我的问题是:

  1. how should one cast this charPtr back into a Python compatible, print-able string? 应该如何将此charPtr转换为兼容Python的可打印字符串?
  2. is the cast operation just mentioned doing what it should be doing? 是刚才提到的演员操作应该做什么?

ctypes.cast() is used to convert one ctype instance to another ctype datatype. ctypes.cast()用于将一个ctype实例转换为另一个ctype数据类型。 You don't need it To convert it to python string. 你不需要它将它转换为python字符串。 Just use ".value" to get it in python string. 只需使用“.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

More info here 更多信息在这里

If you set the argtypes or restype attributes of ctypes functions, they will return the right Python object without the need for a cast. 如果设置ctypes函数的argtypesrestype属性,它们将返回正确的Python对象而无需强制转换。

Here's an example calling the C-runtime time and ctime functions: 这是一个调用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'

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

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