Click here to Skip to main content
11,410,750 members (63,291 online)
Click here to Skip to main content

Unmanaged to Managed calls (C++ to C#) without Regasm

, 10 Jan 2006
Rate this:
Please Sign up or sign in to vote.
A simple way to call a managed method from the unmanaged world.


As .NET is penetrating the development environment day by day, we are having unmanaged and managed code running parallel. These days, managed to unmanaged calls have become very popular. But unmanaged to managed calls are still tedious. So my aim was to make such calls as simple as possible.


Unmanaged to managed calls using Regasm are very common. I have tried a straightforward call from unmanaged C++ code to a managed C# code. The main funda which I worked on are:

  • Each type of .NET Framework application requires a piece of code called a Runtime host to start it. The runtime host loads the runtime into a process, creates the application domains within the process, and loads and executes user code within those application domains. This section explains how to write a runtime host that performs several fundamental tasks.
  • Operating systems and runtime environments typically provide some form of isolation between applications. This isolation is necessary to ensure that code running in one application cannot adversely affect other, unrelated applications.

    Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run.

  • Unmanaged hosting code is used to configure the common language runtime, load it in the process, and transition the program into managed code. The managed portion of the hosting code creates the application domains in which the user code will run and dispatches user requests to the created application domains.

    In my project, I have made an attempt to create a CLRHost to call methods of a managed DLL or EXE. I have done the steps described in the following section.

Using the code

Suppose we have a .NET DLL with a method declaration like this:

using System;

namespace ManagedDll
    public class ManagedClass
        public ManagedClass()

        public int Add(int i, int j)

Now, the C++ code which directly calls this DLL without using Regasm would be:

// ExposeManageCode.cpp : Defines the entry point
//                        for the console application.
// REF : MSDN : Accessing Members Through IDispatch

#include "stdafx.h"
#include <atlbase.h>
#include <mscoree.h>
#include <comutil.h>

// Need to be modified as your directory settings.
#import "C:\\WINNT\\Microsoft.NET\\Framework\\" 
        "v1.1.4322\\Mscorlib.tlb" raw_interfaces_only    

using namespace mscorlib;

int CallManagedFunction(char*, char*, BSTR, int, 
                          VARIANT *, VARIANT *);

int main(int argc, char* argv[])

    VARIANT varArgs[2] ;

    varArgs[0].vt = VT_INT;
    varArgs[0].intVal = 1;

    varArgs[1].vt = VT_INT;
    varArgs[1].intVal = 2;

    VARIANT varRet;
    varRet.vt = VT_INT;
    //Calling manageddll.dll Add() method.
    int iRet = CallManagedFunction("ManagedDll", 
        printf("\nSum = %d\n",varRet.intVal);

    return 0;

int CallManagedFunction(char* szAsseblyName, 
    char* szClassNameWithNamespace,BSTR szMethodName, 
    int iNoOfParams, VARIANT * pvArgs, VARIANT * pvRet)
    CComPtr<ICorRuntimeHost>    pRuntimeHost;
    CComPtr<_AppDomain>            pDefAppDomain;

        //Retrieve a pointer to the ICorRuntimeHost interface
        HRESULT hr = CorBindToRuntimeEx(
            NULL,    //Specify the version 
                     //of the runtime that will be loaded. 
            L"wks",  //Indicate whether the server
                     // or workstation build should be loaded.
            //Control whether concurrent
            //or non-concurrent garbage collection
            //Control whether assemblies are loaded as domain-neutral. 
            //Obtain an interface pointer to ICorRuntimeHost 
        if (FAILED(hr)) return hr;
        //Start the CLR
        hr = pRuntimeHost->Start();
        CComPtr<IUnknown> pUnknown;
        //Retrieve the IUnknown default AppDomain
        hr = pRuntimeHost->GetDefaultDomain(&pUnknown);
        if (FAILED(hr)) return hr;
        hr = pUnknown->QueryInterface(&pDefAppDomain.p);
        if (FAILED(hr)) return hr;
        CComPtr<_ObjectHandle> pObjectHandle;
        _bstr_t _bstrAssemblyName(szAsseblyName);
        _bstr_t _bstrszClassNameWithNamespace(szClassNameWithNamespace);
        //Creates an instance of the Assembly
        hr = pDefAppDomain->CreateInstance( 
        if (FAILED(hr)) return hr;
        CComVariant VntUnwrapped;
        hr = pObjectHandle->Unwrap(&VntUnwrapped);
        if (FAILED(hr)) return hr;
        if (VntUnwrapped.vt != VT_DISPATCH)    
            return E_FAIL;
        CComPtr<IDispatch> pDisp;
        pDisp = VntUnwrapped.pdispVal;
        DISPID dispid;
        DISPPARAMS dispparamsArgs = {NULL, NULL, 0, 0};
        dispparamsArgs.cArgs = iNoOfParams;
        dispparamsArgs.rgvarg = pvArgs;
        hr = pDisp->GetIDsOfNames (
        if (FAILED(hr)) return hr;
        //Invoke the method on the Dispatch Interface
        hr = pDisp->Invoke (
        if (FAILED(hr)) return hr;

        return ERROR_SUCCESS;
    catch(_com_error e)
        //Exception handling.

We need to be careful about some settings like:

  • The managed DLL should be in the right path, i.e., any mapped path, or inside the debug/release folder of the calling C++ project.

MSCOREE.H contains the definition of the interfaces used in this program.

Points of Interest

So it is done. Unmanaged to managed call becomes very simple, we just need to pass the namespace, class name and the method name with the arguments to be passed. If you want more fundas, click here.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Chakrabarty Rajib
Web Developer
United States United States
Rajib is one of the many altruist guy working with Cognizant Technology Solution ... Smile | :)

Comments and Discussions

QuestionWhy it doesn't work? [modified] Pinmembercaimodorro12-Feb-07 1:15 
AnswerRe: Why it doesn't work? PinmemberHristo Konstantinov2-Mar-07 10:22 
GeneralRe: Why it doesn't work? Pinmembercaimodorro4-Mar-07 20:49 
GeneralUse unmenage C lib on C# PinmemberBandoleiro11-Dec-06 1:24 
GeneralDebuggin... PinmembertheDarkBrianer30-Jul-06 6:58 
GeneralSay thanks PinmemberAlexEvans22-Jan-06 19:17 
GeneralUnmanged to managed calls PinmemberSeverian@Severian.org19-Jan-06 21:38 
GeneralRe: Unmanged to managed calls PinmemberClaus Brod22-Jan-06 7:03 

I should probably ignore the troll, but just a few words for those who are irritated by his claims.

Whether .NET is a good thing or not - this article is definitely NOT suited to help you to make that decision for yourself. Why? Because it doesn't contain a single line of managed code, i.e. of what commonly is called ".NET"!

Instead, the article focuses on a rare use case where the programmer needs to integrate unmanaged and managed code, wants to forego the automatisms and tools provided by the .NET framework, and where performance isn't a major issue. Within these confines, this code does its job just fine - thanks to Chakrabarty for working this out and sharing it with us!

The reason why this code looks like COM to you is because it, well, basically *is* COM. The code accesses the CLR from outside through its COM-like interfaces to perform its job.

To integrate managed and unmanaged code, Microsoft provides several mechanisms which are usually preferred. For example, you can automatically create a COM wrapper for your managed code (the "regasm approach") and then use it from your existing managed code just like any other COM component. Or you could use Managed C++ (now C++/CLI) and freely mix managed and unmanaged code in the same executable and even in the same source file. Or you could pass delegate function pointers from the managed code into the unmanaged code and use them to call back into the managed world. Or...

So there are many ways to interface between managed and unmanaged code, and most of them are much more elegant than the one discussed here. (Which does not mean that I want to dis the article - it's just that you should know your options before deciding to use this approach. Again, kudos to Chakrabarty for illustrating another interesting interfacing option.)

Personally, I think that .NET is an extremely interesting and ambitious attempt to raise the abstraction level in software engineering and help everybody to improve their productivity.

GeneralRe: Unmanged to managed calls PinmemberAntony M Kancidrowski13-Jun-06 7:38 
Generalperformance? and what about managed C++ Pinmembernuno8918-Jan-06 17:55 
GeneralRe: performance? and what about managed C++ Pinmemberischen_s118-Jan-06 21:53 
GeneralRe: performance? and what about managed C++ PinmemberAndromeda Shun18-Jan-06 21:53 
GeneralExtending this to Visual Basic 6 Pinmembergoldsun18-Jan-06 14:48 
GeneralThis is nuts PinmemberAndrei Dumitrache17-Jan-06 23:19 
GeneralRe: This is nuts PinmemberDasbose19-Jan-06 5:17 
GeneralRe: This is nuts PinmemberNagy Pityu19-Jan-06 7:26 
GeneralRe: This is nuts PinmemberAndrei Dumitrache19-Jan-06 23:34 
QuestionMind boggling! More on pointers? PinmemberKoushik Biswas11-Jan-06 16:52 
AnswerRe: Mind boggling! More on pointers? PinmemberChakrabarty Rajib13-Jan-06 3:47 
GeneralInteresting PinmemberStephen Hewitt10-Jan-06 16:56 
GeneralRe: Interesting PinmemberChakrabarty Rajib10-Jan-06 20:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150414.5 | Last Updated 10 Jan 2006
Article Copyright 2006 by Chakrabarty Rajib
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid