I need to create a c-function, which should be called from Python - using ctypes - and which should provide an array of strings to the calling python function. I have full control of both environments.
Preferably, it should work with Python 2 and 3.
I have this c-function:
long ProvideTexts(wchar_t** texts, long textCount, long stringMaxSize)
the return value is an error code. texts is the actual array. textCount is the number of elements in the array. stringMaxSize is the maximum size of each string.
I am trying to allocate everything in Python and to have the c++ function overwrite the strings. I am not sure if this is the best way. I figured it was the simplest way to go since the memory will need to be de-allocated in Python.
This is my (non-working) code to create the strings and call the function:
import ctypes
stringMaxSize = 1000
ProvideTextsMethod = loadedDll.ProvideTexts
ProvideTextsMethod.restype = ctypes.c_long
arrayType = ctypes.c_wchar_p * textCount
pyArray = arrayType()
for i in range(0, textCount):
pyArray[i] = ctypes.create_unicode_buffer(stringMaxSize) # fails here
ProvideTextsMethod.argtypes = [arrayType, ctypes.c_long, ctypes.c_long]
errorCode = ProvideTextsMethod(pyArray, textCount, stringMaxSize)
I get this error:
incompatible types, c_wchar_Array_1000 instance instead of c_wchar_p instance
What do I need to change?
You'll need to cast it since pyArray is an array of c_whar_p:
for i in range(0, textCount):
pyArray[i] = ctypes.cast(ctypes.create_unicode_buffer(stringMaxSize), ctypes.c_wchar_p)
Does this help?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments