【发布时间】:2016-06-14 23:21:55
【问题描述】:
我试图弄清楚如何在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 值?
感谢任何帮助。
【问题讨论】:
-
Python 有
char类型吗?或者它只是为c传递一个长度为1的字符串? -
如果你把它称为
mylib.displayargs(10, 99, "hello world!")会发生什么?
标签: python-2.7 ctypes