Python ctypes in_dll字符串分配 [英] Python ctypes in_dll string assignment
问题描述
我可以使用ctypes在DLL中为全局C变量赋值。
以下是我正在尝试的示例:
test.c包含以下内容
#include< stdio.h>
字符名称[60];
无效测试(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
变量,然后使用ctypes接口调用C测试函数,我得到以下信息...
>>从ctypes import *
>> dll = windll.Test
>> dll
< WinDLL Test,在...处处理...>
>> f = c_char_p.in_dll(dll,‘name’)
>>> f
c_char_p(无)
>> f.value =‘foo’
>>> f
c_char_p(’foo’)
>>> dll.test()
名称是名称为4∞┘☺
13
为什么在这种情况下测试功能会打印垃圾?
更新:
我已确认Alex的回答。这是一个工作示例:
>>从ctypes import *
>> dll = windll.Test
>> dll
< WinDLL Test,在...处处理...>
>> f = c_char_p.in_dll(dll,‘name’)
>>> f
c_char_p(无)
>> libc = cdll.msvcrt
>> libc
< CDLL‘msvcrt’,在...处处理...>
#请注意,以下strcpy
>> libc.strcpy(pointer(f),c_char_p( foo))
>> dll.test()
名称为foo
name
并不是一个真正的字符 pointer (它是一个数组,在访问时会腐烂一个指针,但永远不能是分配)。您需要从C运行时库中调用 strcpy
函数,而不是分配给 f.value
。 / p>
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
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
.
这篇关于Python ctypes in_dll字符串分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!