[ACCEPTED]-Is it possible to pass a python string by reference through ctypes?-ctypes

Accepted answer
Score: 17

Assigning a new value to instances of the 19 pointer types c_char_p, c_wchar_p, and c_void_p 18 changes the memory location they point to, not 17 the contents of the memory block (of course 16 not, because Python strings are immutable):

>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> c_s.value = "Hi, there"
>>> print c_s
c_char_p('Hi, there')
>>> print s                 # first string is unchanged
Hello, World
>>>

You 15 should be careful, however, not to pass 14 them to functions expecting pointers to 13 mutable memory. If you need mutable memory 12 blocks, ctypes has a create_string_buffer 11 function which creates these in various 10 ways. The current memory block contents 9 can be accessed (or changed) with the 8 raw property, if you want to access it 7 as NUL terminated string, use the string property:

Says 6 the ctypes tutorial. What I gather from 5 this is that only if the function would 4 work with a const char*, would passing in the python 3 string be valid. Keep in mind, it won't 2 have a null termination.

I'd suggest using 1 create_string_buffer anyhow.

Score: 6

The type ctypes.c_char_p represents a nul-terminated string. If 4 a function takes a const char* you can pass 3 a Python string to it and it will receive 2 a nul-terminated version.

A Windows example 1 DLL:

#include <string.h>

__declspec(dllexport) char* func(char* a,size_t len,const char* b)
{
    if(strlen(b) * 2 >= len)
        return NULL;
    strcpy_s(a,len,b);
    strcat_s(a,len,b);
    return a;
}

Python:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> x=CDLL('x')
>>> x.func.restype=c_char_p
>>> x.func.argtypes=[c_char_p,c_int,c_char_p]
>>> s=create_string_buffer(10)
>>> x.func(s,len(s),'abcd')
'abcdabcd'
>>>

More Related questions