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

前端 未结 2 530
时光说笑
时光说笑 2021-01-04 11:09

I am attempting to cast a C style const char[] string pointer (returned from a DLL) into a Python compatible string type. but when Python27 executes:

import         


        
相关标签:
2条回答
  • 2021-01-04 11:31

    ctypes.cast() is used to convert one ctype instance to another ctype datatype. You don't need it To convert it to python string. Just use ".value" to get it in python string.

    >>> 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

    0 讨论(0)
  • 2021-01-04 11:34

    If you set the argtypes or restype attributes of ctypes functions, they will return the right Python object without the need for a cast.

    Here's an example calling the C-runtime time and ctime functions:

    >>> 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'
    
    0 讨论(0)
提交回复
热议问题