How to convert .Net strings to ANSI strings in managed C++?
Jan
30
Written by:
1/30/2013 7:57 PM
I forgot to give the code used in the precedent webservice sample (Calling a secured webservice in Sophis Risque). These lines make the conversion and release the memory:
1.
#pragma once
2.
3.
4.
#define STRING_TO_CHAR(myString) (char*)(void*)(System::IntPtr)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi( ##myString );
5.
#define RELEASE_CHAR(myString) System::Runtime::InteropServices::Marshal::FreeHGlobal( (System::IntPtr)(void*)##myString );
To put somewhere in a .h file (like DotnetMacros.h).
To use the code, a little sample:
1.
char
* szUsi = STRING_TO_CHAR(_usi);
2.
strncpy_s(usi,length,szUsi,length-1);
3.
RELEASE_CHAR(szUsi);