Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python3 ctypes中以字节形式获取c_char_p值?_Python_C_Python 3.x_Ctypes - Fatal编程技术网

如何在python3 ctypes中以字节形式获取c_char_p值?

如何在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中的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)

我自己找到了这个问题的答案

根据官方的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
接受常量字符指针,因此不需要它。