Python ctypes in_dll string assignment

I could use some help when assigning a global C variable to a DLL using ctypes.

Below is an example of what I'm trying to do:

test.c contains the following

#include <stdio.h> char name[60]; void test(void) { printf("Name is %s\n", name); } 

In windows (cygwin), I create a DLL (Test.dll) as follows:

 gcc -g -c -Wall test.c gcc -Wall -mrtd -mno-cygwin -shared -W1,--add-stdcall-alias -o Test.dll test.o 

When I try to change the name variable and then call the C test function using the ctypes interface, I get the following ...

 >>> from ctypes import * >>> dll = windll.Test >>> dll <WinDLL 'Test', handle ... at ...> >>> f = c_char_p.in_dll(dll, 'name') >>> f c_char_p(None) >>> f.value = 'foo' >>> f c_char_p('foo') >>> dll.test() Name is Name is 4∞┘☺ 13 

Why does the test function print garbage in this case?

Update:

I confirmed Alex's answer. Here is a working example:

 >>> from ctypes import * >>> dll = windll.Test >>> dll <WinDLL 'Test', handle ... at ...> >>> f = c_char_p.in_dll(dll, 'name') >>> f c_char_p(None) >>> libc = cdll.msvcrt >>> libc <CDLL 'msvcrt', handle ... at ...> #note that pointer is required in the following strcpy >>> libc.strcpy(pointer(f), c_char_p("foo")) >>> dll.test() Name is foo 
+4
source share
1 answer

name is actually not a pointer to a character (it is an array that "decays" to a pointer upon access, but can never be assigned ). You will need to call the strcpy function from the C runtime library, rather than assigning f.value .

+5
source

Source: https://habr.com/ru/post/1310271/


All Articles