问题描述
这里是 C# 的相同问题:以字节数组编程方式加载资源
Here the same question for C#: load resource as byte array programmaticaly
所以我有一个资源(只是二进制文件 - 用户数据,并不重要).我需要获取一个指向表示此资源的字节数组的指针,如何执行此操作?资源位于 vs2010(win32 控制台项目)的 Resource Files 中.我想我需要使用winapi的FindResource
、LoadResource
和LockResource
函数.
So I've got a resource (just binary file - user data, dosen't really matter). I need to get a pointer to byte array representing this resource, how to do this ? Resource located in Resource Files of vs2010 (win32 console project). I think i need to use FindResource
, LoadResource
and LockResource
function of winapi.
推荐答案
要获取资源的字节信息,第一步是使用FindResource 或 FindResourceEx.然后,使用加载资源LoadResource.最后,使用 LockResource 获取数据地址并访问 SizeofResource 字节.以下示例说明了该过程:
To obtain the byte information of the resource, the first step is to obtain a handle to the resource using FindResource or FindResourceEx. Then, load the resource using LoadResource. Finally, use LockResource to get the address of the data and access SizeofResource bytes from that point. The following example illustrates the process:
HMODULE hModule = GetModuleHandle(NULL); // get the handle to the current module (the executable file)
HRSRC hResource = FindResource(hModule, MAKEINTRESOURCE(RESOURCE_ID), RESOURCE_TYPE); // substitute RESOURCE_ID and RESOURCE_TYPE.
HGLOBAL hMemory = LoadResource(hModule, hResource);
DWORD dwSize = SizeofResource(hModule, hResource);
LPVOID lpAddress = LockResource(hMemory);
char *bytes = new char[dwSize];
memcpy(bytes, lpAddress, dwSize);
为简洁起见,当然省略了错误处理,您应该检查每个调用的返回值.
Error handling is of course omitted for brevity, you should check the return value of each call.
这篇关于在 C++ 中以编程方式将资源加载为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!