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.

Thursday, August 25, 2011

Macros in C#

Macros are a wonder feature found in C++. It allows you to write a template of sorts and use throughout. I bet you didn't know C# allows for templates too.

There is a wonderful template library built in to visual studio called T4. Just add a new file to your project and change the extension to ".tt"



<#@ template language="C#" #>
// This code was generated by a tool.
// Any changes made manually will be lost
// the next time this code is regenerated.
using System;

public class <#= this.ClassName #>
{
 public static void SayHello()
 {
 Console.WriteLine(”Hello World”);
 }
}
<#+
string ClassName = "MyClass";
#>

When you compile this will make a ".cs" file of the same name automatically. These templates are much more powerful than C macros. You have full access to any assemblies in the GAC (for example XML, Networking, and IO).