Click here to Skip to main content
Licence 
First Posted 10 Jan 2006
Views 110,582
Bookmarked 60 times

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

By | 10 Jan 2006 | Article
A simple way to call a managed method from the unmanaged world.

Introduction

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.

Background

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)
        {
            return(i+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", 
               "ManagedDll.ManagedClass",L"Add",
               2,varArgs,&varRet);
    if(!iRet)
        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;

    try
    {
        //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. 
            STARTUP_LOADER_SAFEMODE | STARTUP_CONCURRENT_GC, 
            CLSID_CorRuntimeHost,
            IID_ICorRuntimeHost,
            //Obtain an interface pointer to ICorRuntimeHost 
            (void**)&pRuntimeHost
            );
        
        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( 
            _bstrAssemblyName,
            _bstrszClassNameWithNamespace,
            &pObjectHandle
            );
        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 (
            IID_NULL, 
            &szMethodName,
            1,
            LOCALE_SYSTEM_DEFAULT,
            &dispid
            );
        if (FAILED(hr)) return hr;
        
        //Invoke the method on the Dispatch Interface
        hr = pDisp->Invoke (
            dispid,
            IID_NULL,
            LOCALE_SYSTEM_DEFAULT,
            DISPATCH_METHOD,
            &dispparamsArgs,
            pvRet,
            NULL,
            NULL
            );
        if (FAILED(hr)) return hr;
        
        pRuntimeHost->Stop();

        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.
  • In the C++ project, we need to include the path C:\PROGRAM FILES\MICROSOFT VISUAL STUDIO .NET 2003\SDK\V1.1\BIN, and C:\PROGRAM FILES\MICROSOFT VISUAL STUDIO .NET 2003\SDK\V1.1\LIB for MSCOREE.H and MSCOREE.LIB.

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.

License

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

Member

Rajib is one of the many altruist guy working with Cognizant Technology Solution ... Smile | :)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionthis is stupid way to call the c# dll just add the c# dll as a reference to the win32 project with /clr option Pinmembera ahole16:47 26 Jun '11  
Questionhow to pass a string to c# from vc++ using the above function Pinmemberkindi0:44 19 Jul '10  
Questionhow would the code change if the constructor for the C# app took arguments? Pinmemberronn kling10:34 21 Apr '10  
QuestionHow to call C# DLL functions from Delphi Pinmembervijay.victory3:01 14 Apr '10  
GeneralWhy it doesn't work if the C# method is static Pinmembermarvinmenaleal4:25 11 Jun '09  
GeneralInteresting information on arguments. PinmemberDoug07169:51 20 Mar '09  
Generalgetting errors - please help urgent Pinmembersanjeevkum4:44 5 Mar '09  
GeneralRe: getting errors - please help urgent PinmemberdrQyH16j876K15:01 23 Jun '09  
GeneralQuestion of calling managed dll from unmanaged c++ [modified] - Please help- Pinmembersanjeevkum17:38 4 Mar '09  
GeneralUnmanaged to Managed, how to pass data by reference PinmemberMustafa Alahwel4:03 19 Feb '09  
GeneralRe: Unmanaged to Managed, how to pass data by reference PinmemberDoug07169:30 20 Mar '09  
QuestionHow about performance? Pinmemberaiflame35:28 30 Jan '09  
QuestionHow to do the same thing with BOOL without parameter? PinmemberMohd Audy15:50 12 Jan '09  
GeneralCool! [modified] PinmemberRabbit639:41 31 Oct '08  
Generalcompilation error with this code PinmemberMember 44819636:58 31 Oct '08  
GeneralRe: compilation error with this code Pinmembermenakerman21:33 1 Dec '08  
QuestionHow to do the same thing but with byte[]? Pinmembermringholm5:18 22 Sep '08  
QuestionExample works but... [modified] Pinmemberapalomba10:43 15 Sep '08  
AnswerRe: Example works but... PinmemberChakrabarty Rajib4:04 5 Oct '08  
QuestionThanks and a remark - release pointers? Pinmembertb20009:16 11 Mar '08  
AnswerRe: Thanks and a remark - release pointers? PinmemberChakrabarty Rajib4:08 5 Oct '08  
QuestionDifferent Directory PinmemberCSpicer10:17 21 Feb '08  
GeneralGood Work! Pinmemberadmcse5:01 8 Jan '08  
QuestionWhy it doesn't work? [modified] Pinmembercaimodorro0:15 12 Feb '07  
AnswerRe: Why it doesn't work? PinmemberHristo Konstantinov9:22 2 Mar '07  

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.

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