I am trying to mount iso file with python on Windows 10. Here is the code:
import ctypes
from ctypes import wintypes
ByteArray8 = wintypes.BYTE * 8
src = r'F:\Backup\ubuntu.iso'
class GUID(ctypes.Structure):
_fields_ = [
("Data1", ctypes.c_long),
("Data2", ctypes.c_short),
("Data3", ctypes.c_short),
("Data4", ByteArray8)
]
guid = GUID(0xec984aec, 0xa0f9, 0x47e9, ByteArray8(0x90, 0x1f, 0x71, 0x41, 0x5a, 0x66, 0x34, 0x5b))
class VIRTUAL_STORAGE_TYPE(ctypes.Structure):
_fields_ = [
('DeviceId', ctypes.c_ulong),
('VendorId', GUID)
]
virtual_storage_type = VIRTUAL_STORAGE_TYPE(1, guid)
handle = wintypes.HANDLE()
Path = ctypes.c_wchar_p(src)
print(
ctypes.windll.virtdisk.OpenVirtualDisk(
ctypes.byref(virtual_storage_type),
Path,
0x000d0000,
0x00000000,
None,
ctypes.byref(handle)
)
)
print(
ctypes.windll.virtdisk.AttachVirtualDisk(
handle,
None,
0x00000001,
0,
None,
None
)
)
It shows two 0 after run, which means the open and attach operation succeed. But no new driver shown in explorer.
I want to know the reason and how to mount .iso file correctly. Here is reference: https://learn.microsoft.com/en-us/windows/win32/api/virtdisk/nf-virtdisk-openvirtualdisk https://learn.microsoft.com/en-us/windows/win32/api/virtdisk/nf-virtdisk-attachvirtualdisk
2 problems with the code:
Functional. By default, disk is closed when its corresponding handle is (which happens automatically when the program ends). So, the disk was opened (and shown in Explorer), but only for a very short period of time (after the AttachVirtualDisk call till program end), so you were not able to see it. To be able to use the disk, either:
Don't stop the program until you're done using the disk (add an input statement at the very end)
Detach the disk lifetime from its handle's one (use ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME flag from [MS.Learn]: ATTACH_VIRTUAL_DISK_FLAG enumeration (virtdisk.h)).
Needless to say that now, you'll have to detach the disk yourself, by either:
Eject it from Explorer
Enhancing code to call DetachVirtualDisk
Also, not sure what are the implications of repeatedly attaching the disk (without detaching it)
Coding - Undefined Behavior generator. Check [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer) for a common pitfall when working with CTypes (calling functions)
code00.py:
Output:
In each of the 2 runs above, the effect is visible in Explorer (according to explanations from the beginning):