我可以使用一些帮助使用ctypes分配DLL中的全局C变量.
以下是我正在尝试的一个例子:
test.c包含以下内容
#include <stdio.h>
char name[60];
void test(void) {
printf("Name is %s\n", name);
}
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
当尝试修改name变量然后使用ctypes接口调用C测试函数时,我得到以下内容......
>>> 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
Run Code Online (Sandbox Code Playgroud)
为什么测试功能会在这种情况下打印垃圾?
更新:
我已经确认了亚历克斯的回应.这是一个工作示例:
>>> 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
Run Code Online (Sandbox Code Playgroud)