Pages

Friday 15 May 2009

C++/CLI Cheat Sheet

My C++/CLI pocket reference...
  • Declare a string

System::String^ myString = "";

  • Declare a null reference

System::String^ myString = nullptr;

  • Pass a string by reference to a method (the reference to the string will be modified, not the string itself since strings are immutable). Use %:

void MyMethod(System::String^% myString)

{

}

  • Declare an array of strings
    cli::array<System::String^>^ stringArray = gcnew cli::array<System::String^>{"Skype","Blogger"};
  • Declare a managed member inside a native class
class IAmNative
{
    gcroot<IAmManaged^ > managedMember;
 
public:
    IAmNative():managedMember(gcnew IAmManaged())
    {
 
    }
};

  • Declare a managed member that will self destroy
#include <msclr\auto_gcroot.h> 
 
class IAmStillNative
{
    msclr::auto_gcroot<IAmStillManaged^> managedMember; // Will be disposed when IAmStillNative is destroyed
 
public:
    IAmStillNative():managedMember(gcnew IAmStillManaged())
    {
    }
};
  • Convert a native STL string to a managed string
System::String^ ToManaged(const std::string& nativeString)
{
    return gcnew System::String(nativeString.c_str());
}
  • The same backwards:

std::string ToNative(System::String^ managedString)
{
   char* str = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(managedString).ToPointer();
 
   std::string result(str);
 
   System::Runtime::InteropServices::Marshal::FreeHGlobal((System::IntPtr)str);
   return result;
}
Things you can do
  • Instantiate managed types, call managed methods from native code provided it compiles with /CLR.
  • Instantiate native types, call native methods from managed code
  • Link to the native types of a mixed static lib (/clr)
  • Declare managed methods that have native types in their signature
Things you can't do
  • Link to the managed types of a mixed static lib
  • Link to managed types in a DLL if those managed types have methods with native types in their signature.