得在管理员权限下执行
#include "pch.h"
#define WINVER _WIN32_WINNT_WIN7
#include
#include
#include
#pragma comment(lib, "Virtdisk.Lib")
#include
#include
#include
using namespace std;
int main()
{
GUID VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT = { 0xec984aec, 0xa0f9, 0x47e9, 0x90, 0x1f, 0x71, 0x41, 0x5a, 0x66, 0x34, 0x5b };
OPEN_VIRTUAL_DISK_PARAMETERS openParameters;
openParameters.Version = OPEN_VIRTUAL_DISK_VERSION_1;
openParameters.Version1.RWDepth = OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT;
VIRTUAL_STORAGE_TYPE openStorageType;
openStorageType.DeviceId = VIRTUAL_STORAGE_TYPE_DEVICE_VHD;
openStorageType.VendorId = VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT;
ATTACH_VIRTUAL_DISK_PARAMETERS attachParameters;
attachParameters.Version = ATTACH_VIRTUAL_DISK_VERSION_1;
void * vhdHandle;
const char* szStr = "D:\\temp\\test.vhd";
WCHAR vhdPath[256];
MultiByteToWideChar(CP_ACP, 0, szStr, strlen(szStr) + 1, vhdPath,
sizeof(vhdPath) / sizeof(vhdPath[0]));
if (OpenVirtualDisk(&openStorageType, vhdPath,
VIRTUAL_DISK_ACCESS_ALL, OPEN_VIRTUAL_DISK_FLAG_NONE,
&openParameters, &vhdHandle) != ERROR_SUCCESS) {
// If return value of OpenVirtualDisk isn't ERROR_SUCCESS, there was a problem opening the VHD
}
// Warning: AttachVirtualDisk requires elevation
if (AttachVirtualDisk(vhdHandle, 0, ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME,
0, &attachParameters, 0) != ERROR_SUCCESS) {
// If return value of AttachVirtualDisk isn't ERROR_SUCCESS, there was a problem attach the disk
}
std::cout << "Hello World!\n";
return 0;
}