3

I am using ctypes in Python to access functions from a shared C library. One of the parameters for one of the functions requires an empty array of the type char to write error messages into. The code for the array in C++ is simple;

char messageBuffer[256];

I would like to write the equivalent in Python so that I can pass an array containing the correct data type to the function. I've tried simply creating and array in Python of length 256, but I get the error message;

mydll.TLBP2_error_message(m_handle, errorCode, messageBuffer)

ArgumentError: argument 3: <class 'TypeError'>: Don't know how to convert parameter 3

Any help is appreciated.

prpowers
  • 65
  • 6
  • Don't know anything about `ctyes` but does [this](https://stackoverflow.com/questions/16699800/python-using-ctypes-to-pass-a-char-array-and-populate-results) help? Not sure if a duplicate. – TomNash Jul 09 '19 at 16:46
  • Please format your question according to [\[SO\]: How to create a Minimal, Complete, and Verifiable example (mcve)](https://stackoverflow.com/help/mcve). Add the *C* function header, and the *Python* code that uses it (not only the call, but also loading the lib, and preparing the stuff for the call). – CristiFati Jul 09 '19 at 17:05

1 Answers1

3

you can use create_string_buffer() function in ctype package

If you need mutable memory blocks, ctypes has a create_string_buffer() function which creates these in various ways. The current memory block contents can be accessed (or changed) with the raw property; if you want to access it as NUL terminated string, use the value property:

>>> from ctypes import *
>>> p = create_string_buffer(3)      # create a 3 byte buffer, initialized to NUL bytes
>>> print sizeof(p), repr(p.raw)
3 '\x00\x00\x00'
>>> p = create_string_buffer("Hello")      # create a buffer containing a NUL terminated string
>>> print sizeof(p), repr(p.raw)
6 'Hello\x00'
>>> print repr(p.value)
'Hello'
>>> p = create_string_buffer("Hello", 10)  # create a 10 byte buffer
>>> print sizeof(p), repr(p.raw)
10 'Hello\x00\x00\x00\x00\x00'
>>> p.value = "Hi"
>>> print sizeof(p), repr(p.raw)
10 'Hi\x00lo\x00\x00\x00\x00\x00'
>>>

To create a mutable memory block containing unicode characters of the C type wchar_t use the create_unicode_buffer() function.

for more information refer: ctype-fundamental-data-types

vicky
  • 547
  • 5
  • 18