June 18, 2012

Calling C# Code from Windbg Extension

It could be useful to write functions in C#, and to call some of those from Windbg plugin. Here is an approach how to achieve this.

Create a new project from Class Library template in Microsoft Visual C# 2010 Express.

Go to project properties an tick Register for COM interop off.

Enable ComVisible by editing AssemblyInfo.cs like below.
[assembly: ComVisible(true)]
Here is a simplified implementation to add.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ExtensionUtils
{
    public interface IManagedInterface
    {
        int Func();
    } 
    public class Utils : IManagedInterface
    {
        public int Func()
        {
            return 1;
        }
    }
}
When compiling the code both ExtensionUtils.tlb and ExtensionUtils.dll have been created.

Open the Windbg plugin in Microsoft Visual C++ 2010 Express.

Add the following code that calls the C# function. But make sure to to copy ExtensionUtils.tlb and ExtensionUtils.dll files to directory that has been added to the (additional) include directories in the project settings.

#import "ExtensionUtils.tlb" named_guids 
[...] 
    HRESULT hRes; 
    CoInitialize(NULL); 
    ExtensionUtils::IManagedInterface *pManagedInterface = NULL; 
    hRes = CoCreateInstance(ExtensionUtils::CLSID_Utils, NULL, CLSCTX_INPROC_SERVER, 
     ExtensionUtils::IID_IManagedInterface, reinterpret_cast<void**> (&pManagedInterface));
    if (hRes == S_OK)
    {
        int ret = pManagedInterface->Func();
    } 
    CoUninitialize();
That's how I did.
  This blog is written and maintained by Attila Suszter. Read in Feed Reader.