Python: ctypes 如何将 c_char_Array 转换成 c_char_p
Python: ctypes how to convert c_char_Array into c_char_p
函数create_string_buffer(b"foo", 3)
returns类型c_char_Array_3
。试图将此传递到预期 c_char_p
的地方会被 TypeError: incompatible types, c_char_Array_3 instance instead of c_char_p instance
炸毁。如何将 create_string_buffer
的输出传递到需要 c_char_p
的字段中?
我想这个人有同样的问题:https://ctypes-users.narkive.com/620LJv10/why-doesn-t-c-char-array-get-coerced-on-assignment-to-a-pointer
但是,我不清楚答案是什么。
您 可以 将 create_string_buffer
对象传递给具有 c_char_p
作为 .argtypes
参数的函数,但当它是一个结构的成员。 cast
可以解决它。您在问题中提供的 link 中提到了这一点。
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)
输出:
b'test'
b'qest'
函数create_string_buffer(b"foo", 3)
returns类型c_char_Array_3
。试图将此传递到预期 c_char_p
的地方会被 TypeError: incompatible types, c_char_Array_3 instance instead of c_char_p instance
炸毁。如何将 create_string_buffer
的输出传递到需要 c_char_p
的字段中?
我想这个人有同样的问题:https://ctypes-users.narkive.com/620LJv10/why-doesn-t-c-char-array-get-coerced-on-assignment-to-a-pointer
但是,我不清楚答案是什么。
您 可以 将 create_string_buffer
对象传递给具有 c_char_p
作为 .argtypes
参数的函数,但当它是一个结构的成员。 cast
可以解决它。您在问题中提供的 link 中提到了这一点。
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)
输出:
b'test'
b'qest'