Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.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
在python2.7中使用ctypes.memset()_Python_Python 2.7_Memset - Fatal编程技术网

在python2.7中使用ctypes.memset()

在python2.7中使用ctypes.memset(),python,python-2.7,memset,Python,Python 2.7,Memset,我正在尝试使用ctypes.memset在python文件中设置一个子字符串 以下是我正在使用的代码: import ctypes def memz(string): buffsize = len(string)+1 size = sys.getsizeof(string) offset = size - buffsize start = string.find('{') -----------> 142 end = string.find('}'

我正在尝试使用ctypes.memset在python文件中设置一个子字符串

以下是我正在使用的代码:

import ctypes

def memz(string):
    buffsize = len(string)+1
    size = sys.getsizeof(string)
    offset = size - buffsize
    start = string.find('{') -----------> 142
    end = string.find('}') + 1  --------> 167
    location = id(string)
    ctypes.memset(location + offset + start, 0, end-start)
我看到这并没有memset子字符串,而是写入内存的其他部分。我怀疑我没有将正确的内存位置传递给ctypes.memset。 是否需要更改传递给ctypes.memset的locationlocation+offset+start的格式


PS:该解决方案源自。我尝试了那个解决方案,但使用了ctypes.CDLL'libc.so.6'中的memset。memset会导致seg故障。我正在使用Python2.7.11。

您的解决方案也很有效。我尝试在本地运行它,它清除了所需的子字符串

str = 'This is a {sample} string'

print(ctypes.string_at(id(str), sys.getsizeof(str)))

buffSize = len(str)+1
size = sys.getsizeof(str)
offset = size - buffSize
start = str.find('{')
end = str.find('}') + 1
location = id(str)

ctypes.memset(location + offset + start, 0, end-start)

print(ctypes.string_at(id(str), sys.getsizeof(str)))
它产生以下输出

 ���A,�5~��dThis is a {sample} string
 ���A,�5~��dThis is a  string

谢谢你尝试一下。我在我的本地机器上也试过了,但在我使用它的地方,它不能作为一个大代码的一部分工作。也许你可以尝试不同的方法来计算从起始位置的偏移量。您可能希望使用startIndex=ctypes.string_atidstring,sys.getsizeofstring.find“{”endIndex=ctypes.string_atidstring,sys.getsizeofstring.find'}”,然后使用memset memset idstring+startIndex,0,endIndex startIndex+1