Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
I';我试图用python ctypes打开一个用c编写的dll并运行其中的函数,但它是以字符而不是字符串的形式出现的_Python_C_Dll_Ctypes - Fatal编程技术网

I';我试图用python ctypes打开一个用c编写的dll并运行其中的函数,但它是以字符而不是字符串的形式出现的

I';我试图用python ctypes打开一个用c编写的dll并运行其中的函数,但它是以字符而不是字符串的形式出现的,python,c,dll,ctypes,Python,C,Dll,Ctypes,以下是我正在研究的代码: #包括 无效测试\打印(字符测试[100]) { printf(“%s”,测试); } 从ctypes导入* libcdll=CDLL(“test.dll”) libcdll.测试打印(“测试”) 但是当我运行程序时,我得到的是“t”而不是“test”。始终为函数设置.argtypes和.restype,以避免头痛ctypes可以验证参数是否正确传递 例如: 测试c #包括 __declspec(dllexport)//在Windows上导出函数需要 void te

以下是我正在研究的代码:

#包括
无效测试\打印(字符测试[100])
{
printf(“%s”,测试);
}
从ctypes导入*
libcdll=CDLL(“test.dll”)
libcdll.测试打印(“测试”)
但是当我运行程序时,我得到的是“t”而不是“test”。

始终为函数设置
.argtypes
.restype
,以避免头痛
ctypes
可以验证参数是否正确传递

例如:

测试c

#包括
__declspec(dllexport)//在Windows上导出函数需要
void test_print(char*test)//衰减到指针,所以char test[100]是误导性的。
{
printf(“%s”,测试);
}
test.py

从ctypes导入*
libcdll=CDLL(“/测试”)
libcdll.test_print.argtypes=c_char_p,#对于(char*)参数,逗号构成元组
libcdll.test_print.restype=None#用于无效返回
libcdll.测试打印(b“测试”)
输出:

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
请注意,如果要传递Python
str
而不是
bytes
,请按如下方式声明C函数,并改用
.argtypes=C\u wchar\p,

void test\u print(wchar\u t*test){
wprintf(L“%s”,test);//printf和格式字符串的宽版本
}

Try
libcdll.test\u print(b“test”)
insteadyep,它可以工作,谢谢:)基于@n.的代词m。我假设以下解释:python
str
对象是unicode字符串,每个字符有2个字节。大多数系统使用小端字节顺序,因此
“test”
在内部表示为
b“t\x00e\x00s\x00t\x00”
。然后,C代码需要一个以
'\0'
结尾的字符串,并在第一个
“t”
之后停止。因此,如果我使用的是定义的变量而不是句子,我是否应该键入libcdll.test_print(b(variable))?@SteryNomo No,
b'xxxx'
只是生成字节字符串文字的语法。为变量分配一个字节字符串,例如
v=b'hello'
,或者如果您有一个Unicode字符串(type
str
),您可以通过将其编码为字节字符串将其转换,例如
v=“hello”;测试打印(v.encode())
。默认编码为
utf-8
。如果您没有看到我的问题,我将永远无法完成我的项目,非常感谢:)