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

Igor stojkovic.igor at gmail.com
Thu Oct 19 15:41:27 UTC 2017


On Monday, 16 October 2017 at 22:54:32 UTC, Adam D. Ruppe wrote:
> 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.

If you will not use this buffer in any other way but as an 
immutable string slightly better way is to:

import std.exception : assumeUnique;
return assumeUnique(buffer[0..ret]);

This will not allocate another buffer only to copy data to it as 
immutable.


More information about the Digitalmars-d-learn mailing list