Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert System::IntPtr to char*

Tags:

c++-cli

can any body tell How to convert System::IntPtr to char* in managed c++ this is my main function

int main(void) 
{
    String* strMessage = "Hello world";

    CManagedClass* pCManagedClass = new CManagedClass();//working
    pCManagedClass->ShowMessage(strMessage);//working


****above said error here***    
       char* szMessage = (char*)Marshal::StringToHGlobalAnsi(strMessage);
    CUnmanagedClass cUnmanagedClass; cUnmanagedClass.ShowMessageBox(szMessage);
    Marshal::FreeHGlobal((int)szMessage);

    return 0;
}

thanks in advance

like image 970
Cute Avatar asked Dec 08 '25 12:12

Cute


2 Answers

I'm not a huge C++/CLI programmer, but the following should work just fine.

IntPtr p = GetTheIntPtr();
char* pChar = reinterpret_cast<char*>(p.ToPointer());

The IntPtr class has a method called ToPointer which returns the address as a void* type. That will be convertible to char* in C++/CLI.

EDIT

Verified this works on VS2008 and VS2015

like image 169
JaredPar Avatar answered Dec 12 '25 06:12

JaredPar


Instead of

char* szMessage = (char*)Marshal::StringToHGlobalAnsi(strMessage).ToPointer();
Marshal::FreeHGlobal((int)szMessage);

Use

marshal_context conversions.
const char* szMessage = conversions.marshal_as<const char*>(strMessage);

It cleans itself up, the magic of C++ RAII.

like image 30
Ben Voigt Avatar answered Dec 12 '25 04:12

Ben Voigt