Python 范围中的ctypes字符串缓冲区
感谢您花时间阅读本文,这让我很烦。我正在使用Python3.8并使用Python 范围中的ctypes字符串缓冲区,python,ctypes,Python,Ctypes,感谢您花时间阅读本文,这让我很烦。我正在使用Python3.8并使用ctypes调用DLL。在大多数情况下,ctypes就像魅力一样 C DLL中的一个函数将输出名称列表,即 int get_date(char* names[]) // each name has length 10, with size of 5 在Python中,我成功地将其称为 string\u buffers=[ctypes.create\u string\u buffer(10)用于范围(5)中的i] char_数组
ctypes
调用DLL。在大多数情况下,ctypes
就像魅力一样
C DLL中的一个函数将输出名称列表,即
int get_date(char* names[]) // each name has length 10, with size of 5
在Python中,我成功地将其称为
string\u buffers=[ctypes.create\u string\u buffer(10)用于范围(5)中的i]
char_数组=(ctypes.c_char_p*5)(*map(ctypes.addressof,string_缓冲区))
handler.get_date(字符数组)
但我试图找出一个函数来创建这种情况:
def create_char_p_数组(长度:int,大小:int):
字符串\u缓冲区=[为范围(大小)中的i创建\u字符串\u缓冲区(长度)]
ia=(c_char_p*size)(*映射(addressof,string_buffers))
返回ia
字符数组=创建字符数组(10,5)
handler.get_date(char_数组)###失败、崩溃或随机值###
因此,为了缩小问题范围,我将地图(addressof)移出,它神奇地工作了!:
def create_char_p_数组(长度:int,大小:int):
字符串\u缓冲区=[为范围(大小)中的i创建\u字符串\u缓冲区(长度)]
返回字符串缓冲区
sbrs=创建字符数组(10,5)
char_数组=(c_char_p*5)(*map(addressof,sbrs))
handler.get_date(字符数组)#成功!
是不是因为函数创建字符数组返回后,在函数作用域中创建的创建字符串\u缓冲区将被清除
谢谢您抽出时间,非常感谢。这是我的想法addressof
不会创建对其操作的对象的引用<代码>强制转换
将
测试c:
#include <string.h>
__declspec(dllexport) int get_date(char* names[])
{
strcpy_s(names[0],10,"One");
strcpy_s(names[1],10,"Two");
strcpy_s(names[2],10,"Three");
strcpy_s(names[3],10,"Four");
strcpy_s(names[4],10,"Five");
return 5;
}
输出:
b'One'
b'Two'
b'Three'
b'Four'
b'Five'
范围不是问题,可达性才是问题。数组对象必须通过一系列Python引用才能访问,否则它们就有资格回收,并且ctypes指针不算作Python引用。因此,在不初始化字符串的情况下会出现错误?@CristiFati,我尝试使用c_char_p(“*size”),但也失败了。我想这就是初始化的目的string@user2357112supportsMonica谢谢你的回复。我有没有可能把这件事弄清楚?这样我就不必每天都(c_char_p*5)(*map(addressof,sbrs))
time@user2357112supportsMonicactypes指针确实创建引用,但在本例中,对象是一个整数(地址)。请看我的答案。
b'One'
b'Two'
b'Three'
b'Four'
b'Five'