Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

c - 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. but when Python27 executes:

import ctypes

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

we get: 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?
  2. is the cast operation just mentioned doing what it should be doing?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...