[英]Python: ctypes how to convert c_char_Array into c_char_p
The function create_string_buffer(b"foo", 3)
returns a type c_char_Array_3
. 函数
create_string_buffer(b"foo", 3)
返回类型c_char_Array_3
。 Trying to pass this in where c_char_p
is expected blows up with TypeError: incompatible types, c_char_Array_3 instance instead of c_char_p instance
. 尝试在预期出现
c_char_p
地方传递该c_char_p
,并TypeError: incompatible types, c_char_Array_3 instance instead of c_char_p instance
。 How do I pass the output of create_string_buffer
into a field that expects c_char_p
? 如何将
create_string_buffer
的输出传递到需要c_char_p
的字段中?
I think this person had the same question: https://ctypes-users.narkive.com/620LJv10/why-doesn-tc-char-array-get-coerced-on-assignment-to-a-pointer 我认为这个人有相同的问题: https : //ctypes-users.narkive.com/620LJv10/why-doesn-tc-char-array-get-coerced-on-assignment-to-a-pointer
However, it's unclear to me what the answer was. 但是,我不清楚答案是什么。
You can pass a create_string_buffer
object to a function with a c_char_p
as an .argtypes
parameter, but not when it is a member of a structure. 您可以将
create_string_buffer
对象传递给带有c_char_p
作为.argtypes
参数的函数,但是不能将其作为结构的成员.argtypes
。 cast
can work around it. cast
可以解决它。 This was mentioned in the link you provided in the question. 您在问题中提供的链接中提到了这一点。
from ctypes import *
class foo(Structure):
_fields_ = [('bar',c_char_p)]
s = create_string_buffer(b'test')
f = foo()
f.bar = cast(s,c_char_p)
print(f.bar)
s[0] = b'q'
print(f.bar)
Output: 输出:
b'test'
b'qest'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.