How to pass a string buffer from python function to C Api via ctype

Viewed 720

I have a C api function with the following prototype which I wish to call from Python 2.6/2.7 via the ctypes module.

C function :

int function_name( char *outputbuffer, int outputBufferSize, 
                   const char *input, const char *somestring2 );

Here outputbuffer is a kind of string buffer in which a string is to be inserted as the output once this function is called on the basis of input and somestring2.

How do we create this buffer (output buffer) in python and what would be the argtype for this function

1 Answers

First, you import the ctypes module. Then you need to load your c dll containing the said function. After that you need to set the argument types and the result type of that function. Finally you create your destination buffer and call your function.

Python:

import ctypes as ct

MAX_BUFSIZE = 100
  
mycdll = ct.CDLL("path_to_your_c_dll")  # for windows you use ct.WinDLL(path)

mycdll.function_name.argtypes = [ct.c_char_p, ct.c_int,
                                 ct.c_char_p, ct.c_char_p]

mycdll.function_name.restype = ct.c_int

mystrbuf = ct.create_string_buffer(MAX_BUFSIZE)
result = mycdll.function_name(mystrbuf, len(mystrbuf), 
                              b"my_input", b"my_second_input")

Working example using strncpy:

import ctypes as ct

MAX_BUFSIZE = 100

mycdll = ct.CDLL("libc.so.6")  # on windows you use cdll.msvcrt, instead

mycdll.strncpy.argtypes = [ct.c_char_p, ct.c_char_p, ct.c_size_t]

mycdll.strncpy.restype = ct.c_char_p

mystrbuf = ct.create_string_buffer(MAX_BUFSIZE)
dest = mycdll.strncpy(mystrbuf, b"my_input", len(mystrbuf))

print(mystrbuf.value)

Python 3 output:

user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python3 --version
Python 3.8.5

user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python3 python_ctypes.py 
b'my_input'

Python 2 output:

user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python2 --version
Python 2.7.18

user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python2 python_ctypes.py 
my_input
Related