Python ctypes 在 DLL 中字符串赋值

5 投票
1 回答
4026 浏览
提问于 2025-04-15 22:54

我需要一些帮助,想用ctypes在DLL中给一个全局的C变量赋值。

下面是我正在尝试的一个例子:

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变量,然后通过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

为什么在这种情况下,测试函数会打印出一些乱码呢?

更新:

我已经确认了Alex的回答。这里有一个可以工作的例子:

>>> 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 个回答

6

name 实际上并不是一个字符 指针(它是一个数组,当你访问它时会“变成”一个指针,但你不能直接把它 赋值 给其他东西)。你需要使用 C 语言运行库里的 strcpy 函数,而不是直接给 f.value 赋值。

撰写回答