gpt4 book ai didi

python - 返回与指针赋值之间的 c_char_p 行为不一致

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:09 25 4
gpt4 key购买 nike

考虑以下 C 函数:

void AssignPointer(char **p) {
*p = "Test1";
}

char* Return() {
return "Test2";
}

现在考虑以下 Python 代码:

import ctypes

lib = CDLL('LibraryPathHere')

lib.AssignPointer.restype = None
lib.AssignPointer.argtypes = (ctypes.POINTER(ctypes.c_char_p),)

lib.Return.restype = ctypes.c_char_p
lib.Return.argtypes = None

def to_python_string(c_str : ctypes.c_char_p) -> str:
return c_str.value.decode('ascii')

现在以下工作:

c_str = ctypes.c_char_p()
lib.AssignPointer(ctypes.byref(c_str))
print(to_python_string(c_str))

但是下面给出了 AttributeError: 'bytes' object has no attribute 'value' :

c_str = lib.Return()
print(to_python_string(c_str))

在第一种情况下,调试器将 c_str 显示为 c_char_p(ADDRESS_HERE)。在第二种情况下,调试器将 c_str 显示为 b'Test2'

这是 Python/ctypes 中的错误还是我做错了什么?

最佳答案

ctypes automatically converts c_char_p 将值返回给字节对象。

Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently converted to native Python types. In other words, if a foreign function has a restype of c_char_p, you will always receive a Python bytes object, not a c_char_p instance.

如果您想要实际的指针值,请使用 ctypes.POINTER(ctypes.c_char) 作为 restype

关于python - 返回与指针赋值之间的 c_char_p 行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53999442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com