Я мог бы использовать некоторую справку по присвоению глобальной переменной C в DLL с использованием ctypes.
Ниже приведен пример того, что я пытаюсь:
test.c содержит следующее
#include <stdio.h>
char name[60];
void test(void) {
printf("Name is %s\n", name);
}
В windows (cygwin) я создаю DLL (Test.dll) следующим образом:
gcc -g -c -Wall test.c
gcc -Wall -mrtd -mno-cygwin -shared -W1,--add-stdcall-alias -o Test.dll test.o
При попытке изменить переменную name
и последующем вызове функции C test с использованием интерфейса ctypes я получаю следующее ...
>>> 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
Почему тестовая функция печатает мусор в этом случае?
Обновление:
Я подтвердил ответ Алекса. Вот рабочий пример:
>>> 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