tags:

views:

1419

answers:

2

Hi 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

+1  A: 

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

JaredPar
Thanks guy.u did well
Cute
+1  A: 

Attention!

I want to add something to JaredPar answer.I don't know where your IntPtr is coming from but you should also use pin_ptr in order to prevent the garbage collector from messing up your memory. I did lot of CLR/Native inter op in the past and using pin_ptr is one of those things that I learnt to do in the hard way.

read the following: click me