我怎样才能 c_char_p 值作为 python3 ctypes 中的字节?

How I can c_char_p value get as a bytes in python3 ctypes?

我对 python3 中的 ctypes 有疑问。

我正在尝试获取 c_char_p 作为 python 字节对象。
以下代码试图将其值作为 python3 字节对象获取。

如何获取字节对象的值?

from ctypes import *

libc = cdll.LoadLibrary("libSystem.B.dylib")
s1 = create_string_buffer(b"abc") # create a null terminated string buffer
s2 = create_string_buffer(b"bc")  # same at above


g = libc.strstr(s1, s2)  # execute strstr (this function return character pointer)
print(g) # print the returned value as integer
matched_point = c_char_p(g) # cast to char_p
print(matched_point.value) # trying to getting value as bytes object (cause segmentation fault here)

我自己找到了问题的答案。

根据官方 Python ctypes 文档,调用 C 函数 return 默认为整数。

所以在调用C函数之前,用restype属性指定return值的类型。

正确的代码示例:

from ctypes import *

libc = cdll.LoadLibrary("libSystem.B.dylib")
s1 = create_string_buffer(b"abc") # create a null terminated string buffer
s2 = create_string_buffer(b"bc")  # same at above


libc.strstr.restype = c_char_p # specify the type of return value  

g = libc.strstr(s1, s2)  # execute strstr (this function return character pointer)
print(g) # => b"bc"      (g is bytes object.)