5
votes

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

The following is an example of what I'm trying:

test.c contains the following

    #include <stdio.h>

    char name[60];

    void test(void) {
      printf("Name is %s\n", name);
    }

On windows (cygwin) I build 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 trying to modify the name variable and then calling 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 have confirmed Alex's response. 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
1
I voted up, but after doing some more checking, I think that there might be something else going on. I believe that the OP's original method of assigning a new string to ctype.c_char_p.value is the correct approach. It works for me. I also think that that the strcpy approach might work here where name is malloc'd with 59+NUL characters, but in another situation could result in a segmentation fault. - Mark Mikofski
one line of code worths thausand words: f = c_char_p();buff="guarda mamma, senza mani!";f.value=buff;cast(f,POINTER(c_char))[0]="G";print(buff). To say f.value= "something" bounds f to something that will live a short life. - FxIII

1 Answers

6
votes

name is not really a character pointer (it's an array, which "decays to" a pointer when accessed, but can never be assigned to). You'll need to call the strcpy function from the C runtime library, instead of assigning to f.value.