【发布时间】:2020-05-22 07:54:08
【问题描述】:
我知道我 can 使用 MultiByteToWideChar 将 ASCII 转换为 unicode 字符串,但我想要一个无 API 的解决方案。唯一的区别是 unicode 是 2 个字节,而 ASCII 是 1 个。
应该是下面这样的,但是不行。
问题是:
void* __malloc(size_t size)
{
return HeapAlloc(GetProcessHeap(), 0, size);
}
void __free(void* p)
{
if (p) HeapFree(GetProcessHeap(), 0, p);
}
wchar_t* ascii_to_unicode(const char* ascii)
{
if (!ascii)
return nullptr;
size_t len;
wchar_t* unicode;
len = strlen(ascii) * 2 + 1;
if (!(unicode = reinterpret_cast<wchar_t*>(__malloc(len))))
return nullptr;
for (size_t i = 0; i < len; i++)
*unicode++ = static_cast<wchar_t>(*ascii++);
return unicode;
}
char* unicode_to_ascii(const wchar_t* unicode)
{
if (!unicode)
return nullptr;
size_t len;
char* ascii;
len = wcslen(unicode) / 2 + 1;
if (!(ascii = reinterpret_cast<char*>(__malloc(len))))
return nullptr;
for (size_t i = 0; i < len; i++)
*ascii++ = static_cast<char>(*unicode++);
return ascii;
}
我想将 strdup 返回的 ASCII 转换为我的自定义 get_module_handle 函数。
char* forwardLib = strdup(address);
char* forwardName = _strchr(forwardLib, '.');
*forwardName++ = 0;
get_module_handle(ascii_to_unicode(forwardLib));
//
void* get_module_handle(const wchar_t* moduleName)
{
#if defined _M_IX86
PPEB pPEB = reinterpret_cast<PPEB>(__readfsdword(0x30));
#elif defined _M_X64
PPEB pPEB = reinterpret_cast<PPEB>(__readgsqword(0x60));
#endif
for (PLIST_ENTRY pListEntry = pPEB->Ldr->InMemoryOrderModuleList.Flink; pListEntry && pListEntry != &pPEB->Ldr->InMemoryOrderModuleList; pListEntry = pListEntry->Flink)
{
PLDR_DATA_TABLE_ENTRY pLdrDataTableEntry = CONTAINING_RECORD(pListEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
if (!__wcsicmp(pLdrDataTableEntry->BaseDllName.Buffer, moduleName))
return pLdrDataTableEntry->DllBase;
}
return nullptr;
}
【问题讨论】:
-
你的代码无效 C.
-
@pmg,添加了 C++ 标签,因为我喜欢
nullptr和演员表。 -
无 API 解决方案 -- 是否包括跨平台解决方案?您应该考虑是否要亲自进行这些转换。另外,为什么是指针,而不是从
std::string和std::wstring转换为/?鉴于您要完成的工作,您的方法是使用std::copy或std::transform的简单 1 或 2 行函数。 -
@PaulMcKenzie,我不想使用 CRT。我正在使用
/NODEFAULTLIB。 -
你也想转换什么 unicode 标准?如果是 UTF-8,则不需要转换,因为所有 ascii 值在 UTF-8 中都是有效的。