本帖最后由 岛国秋刀鱼 于 2024-6-26 18:55 编辑
还可以调用winapi跟帖子上说的一样创建一个共享 然后用py加入这个内存区域下面是大致的方法自己调试
[Python] 纯文本查看 复制代码 import ctypes
from ctypes import wintypes
# 定义Windows API函数和常量
OpenFileMappingA = ctypes.windll.kernel32.OpenFileMappingA
OpenFileMappingA.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.LPCSTR]
OpenFileMappingA.restype = wintypes.HANDLE
MapViewOfFile = ctypes.windll.kernel32.MapViewOfFile
MapViewOfFile.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, ctypes.c_ulonglong]
MapViewOfFile.restype = wintypes.LPVOID
UnmapViewOfFile = ctypes.windll.kernel32.UnmapViewOfFile
UnmapViewOfFile.argtypes = [wintypes.LPCVOID]
UnmapViewOfFile.restype = wintypes.BOOL
CloseHandle = ctypes.windll.kernel32.CloseHandle
CloseHandle.argtypes = [wintypes.HANDLE]
CloseHandle.restype = wintypes.BOOL
# 共享内存名称
shared_memory_name ="MyCustomSharedMemory"
# 打开文件映射对象
file_mapping_handle = OpenFileMappingA(
wintypes.FILE_MAP_ALL_ACCESS, # 访问权限
False, # 是否继承句柄
shared_memory_name # 共享内存名称
)
if file_mapping_handle == 0:
print("Failed to open file mapping object")
exit(1)
# 映射视图
mapped_view = MapViewOfFile(
file_mapping_handle, # 文件映射对象句柄
wintypes.FILE_MAP_ALL_ACCESS, # 访问权限
0, # 高位偏移
0, # 低位偏移
0 # 映射大小(0表示整个文件映射对象)
)
if mapped_view == 0:
print("Failed to map view of file")
CloseHandle(file_mapping_handle)
exit(1)
# 现在你可以使用 mapped_view 来访问共享内存
# 例如,读取或写入数据
# 示例:写入数据到共享内存
data_to_write = b"Hello, Shared Memory!"
ctypes.memmove(mapped_view, data_to_write, len(data_to_write))
# 示例:从共享内存读取数据
buffer = ctypes.create_string_buffer(len(data_to_write))
ctypes.memmove(buffer, mapped_view, len(data_to_write))
print("Read from shared memory:", buffer.value.decode())
# 解除映射视图
if not UnmapViewOfFile(mapped_view):
print("Failed to unmap view of file")
# 关闭文件映射对象句柄
if not CloseHandle(file_mapping_handle):
print("Failed to close file mapping object handle")
|