Friday, August 26, 2011

"Shims" in C++/CLI

I saw this post about writing a plugin DLL for the Optimus Mini Three. The DLL needs to be written in C++ but what if you wanted to write it in .NET (ie C#). C# doesnt allow you to directly write normal DLLs that C++ can call into. Instead you need what is called a "shim". A little piece of glue code.

Here is some example glue code to create a plugin for the Mini Three

#define WIN32_LEAN_AND_MEAN  
#include "windows.h"  
#include "OptPlugin.h" 
 #include <vcclr.h>
template<typename T>
 class Shim : public OptimusMiniPlugin {
 	gcroot obj; 
public: 	
Shim(int f) { obj = gcnew T(f);	}
virtual BOOL __stdcall Paint(HDC hdc){ return obj->Paint( IntPtr(hdc) );} 
virtual void __stdcall OnKeyDown(){ obj->OnKeyDown();} 
virtual LPARAM __stdcall GetInfo(int index) { 
#ifdef _WIN64
  return obj->GetInfo(index).ToInt64();
#else
  return obj->GetInfo(index).ToInt32();
#endif
  } 
};   
PLUGIN_EXPORT(Shim)

"Shim" is a C++ class while SomeDotNetClass is a managed class. PLUGIN_EXPORT is the provided macro from Optimus to create the plugin exports. The key to this is the gcroot. It allows you to reference a managed object from the non-managed class. You then just forward call your calls to the managed class. Create your managed class in a C# assembly and reference it from the C++ dll.

No comments:

Post a Comment