如何在python3 ctypes中以字节形式获取c_char_p值?
我对python3中的ctypes有一个问题 我正在尝试获取一个c_char_p作为python字节对象。如何在python3 ctypes中以字节形式获取c_char_p值?,python,c,python-3.x,ctypes,Python,C,Python 3.x,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_st
下面的代码试图将其值作为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)
我自己找到了这个问题的答案 根据官方的PythonCtypes文档,默认情况下,名为C的函数返回整数 因此,在调用C函数之前,请使用
restype
属性指定返回值的类型
正确的代码示例:
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.)
代码看起来不错,对我来说很有用。奇怪。而且
g
不是空指针?此外,使用libc.strstrstr.argtypes=c\u char\u p,c\u char\u p
只需调用g=libc.strstr(b'abc',b'bc')
。只需创建\u字符串\u缓冲区
即可创建可写缓冲区strstr
接受常量字符指针,因此不需要它。