文号
822926
阅读
7370
回复
2
收藏
1
原始字符串资源分析
2016/07/16
IP:四川

Win32资源(Resources)其实是一块标记为.rsrc的只读内存,使用FindResource、LoadResource、LockResource三步就能直接访问,并且因为是直接访问的这一块内存,所以不需要释放它们。

这其中字符串资源是比较奇特的一种资源。首先,它是16个一组打包存放的,真实的ID并不是字符串表中设定的ID,而是(ID>>4)+1;其次,字符串并不是按照标准的C字符串存放的,也不是等距离存放的,而是先存放一个unsigned short的长度值,再存放0-65535个wchar_t表示的Unicode字符。

其实我们没有必要这么费力地去分析字符串资源,字符串资源最多只有65535个字符,因此分配65536个字符的的wchar_t数组,然后使用LoadString加载即可。

// main.cpp

#include <windows.h>
#include <string.h>

__declspec(thread) static wchar_t g_resstr[65536];

bool LoadResString(HMODULE hmod, unsigned short id)
{
	HRSRC hres = FindResource(hmod, MAKEINTRESOURCE((id >> 4) + 1), RT_STRING);
	HGLOBAL hglb = LoadResource(hmod, hres);
	const wchar_t *ptr = (const wchar_t *)LockResource(hglb);
	int size = SizeofResource(hmod, hres);
	const wchar_t *pend = ptr + size / sizeof (wchar_t);
	int idx = id & 0x000f;
	while(idx > 0 && ptr < pend)
	{
		ptr += 1 + *ptr;
		idx--;
	}
	if(ptr >= pend) return false;
	if(*ptr == 0) return false;
	wmemcpy(g_resstr, ptr + 1, *ptr);
	g_resstr[*ptr] = 0;
	return true;
}

int main()
{
	LoadResString(NULL, 1001);
	MessageBox(NULL, g_resstr, L"资源字符串", MB_OK);

	return 0;
}
</string.h></windows.h>
[ 修改于10年0个月前 - 2016/12/21 23:56:28 ]
acmilan作者
10年5个月前修改于 10年0个月前IP:四川
822927
1楼

使用字符串资源的传统方法是使用LoadString,分配65536个字符的数组即可。

// main.cpp

#include <windows.h>

__declspec(thread) static wchar_t g_resstr[65536];

int main()
{
	LoadString(NULL, 1001, g_resstr, 65536);
	MessageBox(NULL, g_resstr, L"资源字符串", MB_OK);

	return 0;
}
</windows.h>
引用
评论
acmilan作者
10年5个月前修改于 10年0个月前IP:四川
822937
2楼
将字符串都转移到资源中的好处是可以对字符串进行翻译,可以同时储存多种语言的字符串,便于实现本地化。系统会根据需要载入适当的字符串。
引用
评论
笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的