I want to get characters of a string pointed by a position memory pointer in native C++:
For an equivalent implementation in C#, it will be:
int positionMemory = getPosition();
long size = 10;
string result = Marshal.PtrToStringAnsi(new IntPtr(positionMemory), size);
How can I produce the result in C++?
I have a feeling this is going to cause problems down the road…
The following should be more or less equivalent to the C# snippet you gave with the exception that the resulting string (stored in
result) will still be ‘ANSI’ – it is not widened to UNICODE as would occur in the C# snippet.Note that
sizecharacters will be placed inresult– including'/0'characters, so if you try to pass the string to something expecting a C-style sting usingc_str()you may get some unexpected results.Also, the usual caveats about using an
intas a pointer (especially if you want this to have a hope of working on a 64-bit system) apply.