user3691223
user3691223

Reputation: 353

Wrong return type when calling function from dll in Python

I have function in DLL and try to call it in Python 3. Function prototype is:

__declspec(dllexport) char* getmetadata(char* szFile, size_t* metadata_size);

Python code is:

...
libm = ctypes.CDLL("libm.dll")
fc = libm.getmetadata
fc.restype = ctypes.c_char_p
fc.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_size_t)]
size = ctypes.c_size_t(0)
buffer = fc(bytes(path, "utf8"), ctypes.byref(size))

Type of buffer is bytes. Why it is not c_char_p?

Upvotes: 1

Views: 590

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177674

ctypes converts c_char_p to Python's native bytes type automatically. It's a convenience:

from ctypes import *
dll = CDLL('msvcrt')
dll._getcwd.argtypes = c_char_p,c_int
dll._getcwd.restype = c_char_p
out = create_string_buffer(30)
print(dll._getcwd(out,30))

Output:

b'C:\\Users\\xxx\\Desktop'

But use something besides c_char_p and you will get a ctypes object:

dll._getcwd.restype = POINTER(c_byte)
result = dll._getcwd(out,30)
print(result)
print(string_at(result))

Output:

<__main__.LP_c_byte object at 0x0000000002C81248>
b'C:\\Users\\xxx\\Desktop'

Upvotes: 1

Related Questions