python、C、ctypes 和一个奇怪的字符

python, C, ctypes and a strange character

我正在尝试了解如何在 python 代码中使用 C 函数。看起来到目前为止最简单的解决方案是使用 ctypes。然而,出于某种原因,在我创建一个导入到 python 的库后,我看到了奇怪的行为。下面提供了所有详细信息。

这是我的 C 代码:

/* mymodule.c */
#include <stdio.h>
#include "mymodule.h"
void displayargs(int i, char c, char* s) {
  (void)printf("i = %d, c = %c, s = %s\n", i, c, s);
}

/* mymodule.h */
void displayargs(int i, char c, char* s)

我使用以下命令从中构建了一个库:

gcc -Wall -fPIC -c mymodule.c
gcc -shared -Wl,-soname,libmymodule.so.1 -o libmymodule.so mymodule.o

我的Python测试代码是这样的

#!/usr/bin/python

# mymoduletest.py
import ctypes

mylib = ctypes.CDLL('./libmymodule.so')
mylib.displayargs(10, 'c', "hello world!")

当我运行./mymoduletest.py我希望看到

i = 10, c = c, s = hello world!

然而我看到了

i = 10, c = �, s = hello world!

为什么显示 个字符而不是 c 的实际 char 值?

感谢任何帮助。

您需要指定函数的参数和return类型:

mylib.displayargs.argtypes = (ctypes.c_int, ctypes.c_char, ctypes.c_char_p)
mylib.displayargs.restype = None  # None means void here.

如果你不指定类型,Python 必须猜测,当你传递一个字符串时它所做的猜测是函数想要一个 char *.