c – 将memcpy放入原始内存位置的向量中

我正在使用一个API,它在内存中提供了感兴趣的字符串的内存地址和长度.我想把这些字符串读成更友好的对象,比如wstring.

对于较小的字符串,使用以下代码可以很好地使用静态大小的缓冲区:

// This code works (but may have other issues)
// _stringLengthOffset and _bufferOffset are provided earlier by the API
// stringOID is the memory location of the string (and in terms of the API, the ObjectID)
DWORD stringLength;
memcpy(&stringLength, ((const void *)(stringOID + _stringLengthOffset)), sizeof(DWORD));
wchar_t argString[DEFAULT_ARGVALUE_BUFFER_SIZE];
memcpy(argString, ((const void *)(stringOID + _bufferOffset)), (stringLength) * sizeof(wchar_t));
argString[stringLength] = L'\0';  // Strings are not null terminated in memory
wstring argumentValue = argString;

我不认为创建一个非常非常大的静态大小缓冲区是个好主意(这些字符串可能有20,000个字符或更多.)我尝试了几种不同的方法,这些代码看起来很接近但不起作用.

// This code does NOT work. 
vector<wchar_t> buffer;
buffer.reserve( stringLength + 1 );
memcpy( &buffer[0], (const void *)(stringOID + _bufferOffset), (stringLength) * sizeof(wchar_t) );
buffer.push_back( L'\0' );
buffer.shrink_to_fit();
wstring argumentValue( buffer.begin(), buffer.end() );

问题:如果目标是创建一个wstring,那么如何从原始内存(由此特定API提供)正确复制到动态大小的缓冲区中,然后创建一个wstring?
(如果之前已经回答道歉,因为看起来像我之前的人会问过但我找不到合适的问题/答案,只需要几个小时的搜索.)

解决方法:

有很多方法.

1)使用resize而不是reserve并执行memcpy.也摆脱了收缩配合.

2)直接分配给字符串:

const wchar_t* pstr = reinterpret_cast<const wchar_t*>(stringOID + _bufferOffset);
wstring s(pstr, pstr + stringLength);
// or:
wstring s(pstr, stringLength);

选项2)避免复制并另外初始化调整大小的向量.

上一篇:android-mmap之后在memcpy中获取分段错误SIGSEGV


下一篇:thinkphp隐藏中url的index.php