Python中的ctypes c_char_p_array_64对象

2024-03-28 23:06:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从python中的DLL文件加载和调用函数。 我的部分代码如下:

listdyn= (ctypes.c_char_p * len(list1_))(*list1_)

print type(listdyn)

输出:main.c_char_p_数组_64'

我应该对c_char_p(或字符串)执行位操作

我有两个问题

1)listdyn是通过这种方式成为指针的指针吗?在

2)如何转换为字符串或字符


Tags: 文件字符串代码lenmaintype数组ctypes
1条回答
网友
1楼 · 发布于 2024-03-28 23:06:19

2)如何转换为字符串或字符 如果list1_中只有字符串值,则使用下一个代码将listdyn转换为字符串:

print ''.join([ctypes.cast(i, ctypes.c_char_p).value for i in listdyn])

或者简单地说(正如eryksun正确地注意到的那样):

^{pr2}$

但问题是,list1_中可能有int值。E、 g.:

^{3}$

字符串对象的值('Demo''''string'和{})可以通过它们的(objects)地址找到,但是int值(0和123)将作为地址(0x00和0x7b=123,以十六进制形式)存储在c_char_p_数组中。因此,如果您尝试使用代码获取第5项(123)的值:

print ctypes.cast(listdyn[5], ctypes.c_char_p).value,在Windows上将发生下一个错误:

ValueError: invalid string pointer 0x000000000000007B

但是在Linux下会出现分割错误。在

因此,如果int值在Windows下的list1_中,请尝试使用以下代码:

result_list = []
listdyn_addr = (ctypes.c_void_p * len(listdyn)).from_buffer(listdyn)
for i in xrange(0, len(listdyn)):
    str_pointer = listdyn_addr[i]
    try:
        value = ctypes.c_char_p(str_pointer).value
        if value == '':
            result_list.append('')
        else:
            result_list.append(0 if not value else value)
    except:
        result_list.append(str_pointer)
print result_list

结果:

['Demo', '', 'string', 0, 'value', 123]

相关问题 更多 >