How do I convert a LPVOID (void*) to string?

Adam D. Ruppe destructionator at gmail.com
Mon Oct 16 22:54:32 UTC 2017


On Monday, 16 October 2017 at 21:48:35 UTC, Nieto wrote:
> How do I convert/create a D string from LPVOID (void*)?

There is no one answer to this, but for the specific function are 
are looking at, the ALLOCATE_BUFFER argument means it puts the 
pointer in the pointer.

So the way I'd do it is:

char* lpMsgBuf;

instead of LPVOID. You might as well keep some type info there; 
no need to call it VOID yet (it will implicitly cast to that when 
it is necessary).

You still need to cast at the function call point, so the rest 
remains the same, but you should keep the return value of 
FormatMessageA.

Then, you can do something like this:

string s = lpMsgBuf[0 .. returned_value].idup;

and it will copy it into the D string.


You could also skip that ALLOCATE_BUFFER argument and pass it a 
buffer yourself, soemthing like:


char[400] buffer;

auto ret = FormatMessageA(
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		errorMessageID,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		buffer.ptr,
		buffer.length, NULL);

return buffer[0 .. ret].idup;


would also work.


More information about the Digitalmars-d-learn mailing list