Saturday, 15 September 2012

c++ - Working with WinAPI functions which use C style strings as OUT parameters -



c++ - Working with WinAPI functions which use C style strings as OUT parameters -

given winapi function returns it's result via c style string out parameter e.g.:

int winapi getwindowtextw( _in_ hwnd hwnd, _out_ lptstr lpstring, _in_ int nmaxcount );

is there improve way of using function i'm doing below?

hwnd handle; // assume initialised contain real window handle std::wstring title; wchar_t buffer[512]; getwindowtextw(handle, buffer, sizeof(buffer)); title = buffer;

the above code works, have next issues it:

the buffer size arbitrary since have no way know length of string function might return. "feels" wrong me - have tried avoid magic numbers in code.

if function returns string larger buffer, truncated - bad!

whenever function returns string smaller buffer, wasting memory. not bad (2), i'm not thrilled thought of setting aside big chunks of memory (e.g. 1024 bytes in illustration above) might need few bytes in practice.

are there other alternatives?

call function multiple times temporary buffers of different sizes. begin buffer of, say, 8. double buffer size , phone call again. repeat until returns same count lastly time. can allocate exact size buffer , re-create you've got there. there number of win32 functions similar behavior.

you may utilize getwindowtextlength(), won't help much if there race conditions (you may end truncated text because of them).

c++ winapi cstring out

No comments:

Post a Comment