我试图在python中调用c函数,这是我的代码
string.c
#include <stdio.h>
int print(const char *str)
{
printf("%s", str):
return 0;
}
字符串.py
from ctypes import *
so_print = "/home/ubuntu/string.so"
my_functions = CDLL(so_print)
print(my_functions.print("hello"))
当我运行python脚本时,它只打印字符串的第一个字符示例";h〃;
我如何传递任何字符串,我的c代码将读取并显示它。
您的函数接受一个const char*
,它对应于Pythonbytes
对象(强制为c_char_p
(,而不是str
对象(强制至c_wchar_p
(。您没有告诉Python底层C函数的原型是什么,所以它只是将str
转换为c_wchar_p
,并且UTF-16或UTF-32编码的仅包含ASCII字符的字符串看起来像是空的或单个字符(取决于平台端序(的C样式char *
字符串。
需要改进的两件事:
-
定义
print
的原型,以便Python在您滥用它时可以警告您,并添加:my_functions.print.argtypes = [c_char_p]
在使用函数之前。
-
将
str
参数编码为bytes
,以便将其转换为有效的C样式char*
字符串:# For arbitrary string, just encode: print(my_functions.print(mystr.encode())) # For a literal, you can pass a bytes literal print(my_functions.print(b"hello")) # ^ b makes it a bytes, not str
您必须在此处进行以下更改。
- 传递字节对象而不是字符串
这是因为根据c
中的基本数据类型c_char_p
是python的字节对象等效类型
from ctypes import *
so_print = "string.so"
my_functions = CDLL(so_print)
print(my_functions.print(b"hello"))