我正在尝试用 python ctypes 和 运行 中的函数打开一个用 c 编写的 dll,但它是一个字符,而不是一个字符串

I'm trying to open a dll written in c with python ctypes and run the function in it, but it comes as a char, not a string

这些是我正在处理的代码:

#include <stdio.h>

void test_print(char test[100])
{
        printf("%s", test);
}

from ctypes import *
libcdll = CDLL("test.dll")

libcdll.test_print("test")

但是当我 运行 程序时,我得到的是“t”而不是“test”。

ALWAYS 为您的函数设置 .argtypes.restype 以减轻头痛。 ctypes 可以验证参数是否正确传递。

示例:

test.c

#include <stdio.h>

__declspec(dllexport)        // required for exporting a function on Windows
void test_print(char* test)  // decays to pointer, so char test[100] is misleading.
{
        printf("%s", test);
}

test.py

from ctypes import *
libcdll = CDLL("./test")
libcdll.test_print.argtypes = c_char_p,  # for (char*) arguments, comma makes a tuple
libcdll.test_print.restype = None       # for void return
libcdll.test_print(b"test")

输出:

test

如果在 OP 问题中用“test”调用,现在它会告诉你参数错误:

Traceback (most recent call last):
  File "C:\test.py", line 5, in <module>
    libcdll.test_print("test")
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type

没有 .argtypesctypes 默认将“测试”从 Python str 转换为 wchar_t* 编码为 UTF-16LE on Windows,所以它看起来像下面这样,printf 将在第一个空字节 (\x00) 处停止,将 t 解释为输出。

>>> 'test'.encode('utf-16le')
b't\x00e\x00s\x00t\x00'

注意,如果要传递Python str而不是bytes,请将C函数声明如下并使用.argtypes = c_wchar_p,代替:

void test_print(wchar_t* test) {
        wprintf(L"%s", test);  // wide version of printf and format string
}