0

I am a beginner with ctypes and I can not figure out how to turn char array into a string in python. I have started using :

create_string_buffer(bytes(var, 'utf8')) to populate an array, but had no luck with getting it back as a string using "byref()".

If someone has any idea you would be a life saver. Thanks in advance!

CristiFati
  • 38,250
  • 9
  • 50
  • 87
  • Did you try: https://stackoverflow.com/questions/8875185/casting-into-a-python-string-from-a-char-returned-by-a-dll – unholy_me Jun 04 '18 at 10:06

1 Answers1

0

ctypes page: [Python]: ctypes - A foreign function library for Python.
It's hard to tell without seeing some code, but here's an example:

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

Notes:

CristiFati
  • 38,250
  • 9
  • 50
  • 87
  • The solution is quite ugly indeed : cp = create_string_buffer(bytes(" ", 'utf8')) **<--- keep in mind the spaces** and then getting it using `byref(cp)` from inside the function, you get the object str(cp.value) finally returns the desired string/path I have no idea why it works, so if someone could elaborate me a bit on this python madness i'd appreciate it. Thanks – giliathfreak Jun 07 '18 at 09:31
  • So the argument is an inout one. I modified the code to reflect that. As I said at the beginning, it's hard to guess what happens in your case without any code. For a proper understanding, the *Python* code that calls the function should be available, and also the *C* function declaration. – CristiFati Jun 07 '18 at 09:43