私は、対象の文字列のメモリ アドレスと長さをメモリ内で提供する 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 を作成するにはどうすればよいですか? (これが以前に回答されていた場合は申し訳ありません。以前に誰かが尋ねたように思えますが、数時間検索しても適切な質問/回答を見つけることができませんでした。)