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
ctypes.py_object is a type. ctypes.py_object * size is a type. ctypes.py_object() is an instance of a type.
It is a big C++ codebase with a (very) thin python wrapper which uses CDLL to load the C++ and call some C functions that are available to allow primitive python scripting of the code.
c_char_p is a subclass of _SimpleCData , with _type_ == 'z' . The __init__ method calls the type's setfunc , which for simple type 'z' is z_set . In Python 2, the z_set function (2.7.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With