The reason to write C++/CLI rather than C# is that one file, and one function, can hold managed and native code. The compiler writes the code that crosses between them, a thunk, wherever a managed function calls a native one or the other way round. Microsoft calls the feature C++ Interop, and the community calls it It Just Works (IJW).
The two ways to call native code
| C++ Interop (IJW) | Explicit P/Invoke | |
|---|---|---|
| how | include the native header and call the function: MessageBeep(0); | declare the function with [DllImport("user32.dll")] and call it |
| marshalling | none by the runtime: the types are the native types; the program converts managed data itself | the runtime marshals the arguments as the attribute says (CharSet, MarshalAs) |
| needs | the header and the import library of the native code | only the name of the DLL |
| available in | C++/CLI only | every .NET language |
// implicit: the compiler makes the transition
#include <windows.h>
void Beep() { MessageBeep(MB_OK); }
// explicit
using namespace System::Runtime::InteropServices;
[DllImport("user32.dll", CharSet = CharSet::Unicode)]
extern "C" int MessageBoxW(IntPtr hwnd, String^ text, String^ caption, unsigned type);
Where the native source is available and the types are blittable (the same size and layout in both worlds), C++ Interop is the shorter way and the type-safer one. Explicit P/Invoke is the way when only the name of the DLL is known, or when the runtime should marshal the arguments. C++ Interop also reaches COM directly (CoCreateInstance, QueryInterface) without an interop assembly, which is why wrappers of COM components are often written in C++/CLI.
Marshalling strings
#include <msclr/marshal_cppstd.h>
using namespace msclr::interop;
std::string ToNative(System::String^ s) { return marshal_as<std::string>(s); }
System::String^ ToManaged(const std::string& s) { return marshal_as<System::String^>(s); }
// older, explicit forms
IntPtr p = Marshal::StringToHGlobalAnsi(s);
const char* c = static_cast<const char*>(p.ToPointer());
// ... use c ...
Marshal::FreeHGlobal(p);
// the characters of a String without copying them: an interior pointer
#include <vcclr.h>
pin_ptr<const wchar_t> w = PtrToStringChars(s);
The marshalling library is msclr/marshal.h, marshal_cppstd.h and marshal_windows.h: marshal_as<T> converts one value, and marshal_context owns the memory of a conversion that needs it (such as to const char*). Arrays are marshalled by pinning the first element or by copying with Marshal::Copy, and structures with Marshal::StructureToPtr and PtrToStructure.
Holding managed objects in native code
#include <vcclr.h>
class NativeHolder {
gcroot<System::String^> text; // a handle in a native class
public:
NativeHolder(System::String^ s) : text(s) {}
void Print() { System::Console::WriteLine(text); }
};
A native class cannot contain a handle directly, because the collector cannot see inside it. gcroot<T^> (header vcclr.h) wraps a GCHandle: the object stays alive while the gcroot exists, and the handle is freed by its destructor. msclr::auto_gcroot<T^> (msclr/auto_gcroot.h) also deletes the object. A value type can be held with a boxed handle in the same way.
Callbacks
A managed delegate can be given to native code as a function pointer with Marshal::GetFunctionPointerForDelegate. The delegate must stay reachable for as long as native code may call it, so it is kept in a field or in a GCHandle. A native function pointer to a managed function declared __clrcall is a managed pointer that cannot be converted to a native one.
Thunks and double thunking
A call from managed code to a native function goes through a managed-to-native thunk, and a call from native code to a managed function goes through a native-to-managed thunk, which finds the right application domain. A managed function whose address is taken, and that is called through a native function pointer, defaults to the native calling convention: the call goes native, thunk to managed, and then back: double thunking. Declaring the function (and the pointer) __clrcall, or compiling the module with /clr:pure in the versions that had it, avoids it, because a managed-only pointer stays inside the runtime.
The loader lock and initialization
A mixed assembly that has native code to start (DllMain, native globals) is loaded by the operating-system loader, which holds the loader lock while it runs that code; managed code may not run under the lock, because the runtime needs the lock too. The global variables of the native part are initialised first, and those of the managed part just before any managed code runs. #pragma init_seg affects the order inside each of the two groups only. The Microsoft pages on the initialization of mixed assemblies describe the rules and the workarounds (for example, not writing a DllMain that calls managed code).
Not described
Known, not yet covered
- Reference: the headers and functions of the marshalling library,
cliext, the pages on marshalling arrays, structures, embedded pointers and function pointers, the initialization of mixed assemblies and the rules of AppDomain transitions were not read in full. The header names and the shapes ofmarshal_as,gcrootandauto_gcrootare those of the Microsoft documentation as remembered, not checked line by line here.
Unknown
- Reference: none of the examples was compiled (see the overview).