Reputation: 6282
If I wanted to fill a vector with a struct, and in the struct I need to dynamically allocate/relocate the WCHAR
arrays, how would I populate this?
I can't use std::wstring
because I'm going to be using the members with the Windows API.
And functions like RegQueryValueEx
require a LPBYTE
to receive the data.
Or is there some other STL container I should be using?
Example Code:
typedef struct {
WCHAR *str1;
WCHAR *str2;
DWORD SomeOtherStuff;
} MYSTRUCT;
vector<MYSTRUCT> myvector;
Upvotes: 1
Views: 1481
Reputation: 254751
Use std::vector<WCHAR>
for the structure members. This will give your structure the necessary copy/move semantics to put it in a vector
and, when you need a raw pointer for some API, it's avaiable as &str1[0]
.
Remember to make sure it's large enough (either by initialising it to the required size, or calling resize()
) before doing anything that will access the data. Also remember that pointers and iterators to the data will become invalid when the vector is resized.
Upvotes: 2
Reputation: 9172
You could define a copy constructor, assignment operator, and destructor for your struct. And then all the copies made of each instance would have their own copy of the dynamically allocated memory.
Or you could just use std::wstring
std::wstring
provides an accessor method c_str
, which gives you a pointer to the underlying null-terminated string. This lets you use std::wstring with C APIs.
std::wstring wide_string;
some_win_api_call( wide_string.c_str() ); // sending a string to winapi
To get a string from the winapi, you need to allocate a buffer yourself, and pass in a pointer to the buffer, along with the length of the buffer.
wide_string.reserve( 256 ); // allocate some space to receive a string
get_string_from_winapi( &wide_string[0], wide_string.capacity() );
You might need to do wide_string.capacity() * sizeof(wchar_t)
if the api wants the length in bytes. My example assumes length in characters.
Upvotes: 0