How To Call A Managed Dll From Unmanaged Code

I here illustrate how a dll written in C# is called in C++ (without CLR).

Make a DLL in C#

Let’s make a small dll (MathLibrary.dll) in C# which provides a public API for adding two numbers. Start Visual Studio, start a new project in Visual C# and select the type of the project as class library. This is how my code for DLL looks like.


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

namespace MathLibrary
{
   public interface IAddClass
   {
      int Add(int a, int b);
   }
   public class CAddClass : IAddClass
   {
      public int Add(int a, int b)
      {
         return a+b;
      }
   }
}

It has a namespace MathLibrary which contains an interface IAddClass and its implementation CAddClass. The public API Add(int a, int b) is provided which can add two numbers supplied.

We have to attach a key file to our DLLl. To generate the key file, go to Visual Studio command prompt (From Start menu –> Programs –> Microsoft Visual Studio 2005 –> Visual Studio Tools). n the command prompt, type

sn.exe -k MyKeyFile.SNK

You can see that MyKeyFile.SNK is generated in the visual studio directory (the command prompt will display where it has been generated). Copy it to the source directory of the dll.  Now edit the AssemblyInfo.cs in visual studio and add/edit the following lines.

[assembly: ComVisible(true)]
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("MyKeyFile.SNK")]

Make sure that MyKeyFile.SNK is in the correct path specified.

Now you can build the DLL (or press Ctrl + Shift + B).

Copy the dll to the directory of the source (C++ program withour CLR option) from where it is to be called.

Register the DLL

Now you have to register the managed dll for using in the unmanaged C++ code. Again take the visual studio command prompt and enter the following command.

RegAsm.exe [including full path] MathLibrary.dll /tlb:MathLibrary.tlb /codebase

We have generated a TLB file, which  contains the type library of different types used in the DLL. The dll is now registered and ready for use in unmanaged code.

Call the DLL from Unmanaged code

The .NET component (dll) can be used as a COM in unmanaged code. So a sample code is provided below which uses the managed DLL as COM.

#include "stdafx.h"
#include <iostream>

// Import the type library in DLL
#import "MathLibrary.tlb" raw_interfaces_only

using namespace MathLibrary;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
   // Initialize the COM interface
   HRESULT hr = CoInitialize(NULL);
   // Make a smart pointer to the IAddClass interface in DLL
   IAddClassPtr pIAddClass(__uuidof(CAddClass));   
   // Add two numbers using the ADD API
   long result = 0;
   hr = pIAddClass->Add(10, 20, &result);
   // Release the COM interface
   CoUninitialize();
   // Display the results
   cout << result << '\n';  
   return 0;
}


About these ads

17 Responses to How To Call A Managed Dll From Unmanaged Code

  1. Your Reader says:

    Great! Thank you!
    I always wanted to write in my blog something like that. Can I take part of your post to my site?
    Of course, I will add backlink?

    Sincerely, Timur I.

  2. cppkid says:

    Sure.
    Please keep watching the blog.
    Thanks.

  3. Gerges says:

    Очень интересно!!! Только не очень могу понять как часто обновляется ваш блог?

  4. rasensio says:

    Hi buddy, I’m dealing with a probelm when trying to register with regasm, maybe you had the same issue.

    RegAsm.exe MyCom.dll /tlb:MyCom.tlb /codebase

    I get

    RegAsm : error RA0000 : Could not load file or assembly ‘MyCom, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=6916412efbdcbd0c’ or one of its dependencies. S
    trong name validation failed. (Exception from HRESULT: 0x8013141A)

    any clue ?

  5. Jimit Shah says:

    Hi,

    I am new to development in VC++. I think this solution is wonderful. I have a small problem similar to this.
    I have a .dll file which is made in .Net 2.0. I do not have any source code available with me. Can you let me know how can I make use of this managed .dll file in my unmanaged code.

    As per my understanding I won’t be able to link the .SNK file with my managed .dll file. Please help, it’s urgent.

  6. Bill Weber says:

    This is total plagiarism. The least you could have done was admit that it was your version of the Microsoft article and gave the web reference:

    http://support.microsoft.com/kb/828736

    What a dweeb.

  7. Prabhat says:

    Hi,what about to run this program to the other PC on which .Net Framework is not installed.
    How to register .tlb file on other PC if we do not want
    to .Net Framework on other PC.
    Is it always necessary to have .Net Framework support
    to register .tlb file.

  8. Prabhat says:

    Hi,what about to run this program to the other PC on which .Net Framework is not installed.
    How to register .tlb file on other PC if we do not want
    to .Net Framework on other PC.
    Is it always necessary to have .Net Framework support
    to register .tlb file.
    Please suggest.

  9. MicrosoftKiD says:

    lol, this sample was taken from Microsoft KB: http://support.microsoft.com/kb/828736

  10. Jott says:

    IAddClassPtr is not defined.
    I have no clue of all this… would it be possible to explain it an even more “idiot proof” way?

  11. andonico says:

    where is IAddClassPtr declared? someone can explain this please.

  12. anonimzer says:

    he can’t explain ‘cos this is a CRP ( copy, Replace variable names ,paste ) article.

  13. “How To Call A Managed Dll From Unmanaged Code This site has been moved to http://techievibes.
    com” was indeed a really excellent posting, . I hope you keep authoring and I’m going to keep on reading through! Thank you ,Erick

  14. […] Kali ini saya akan mencontohkan cara membuat sebuah kelas dalam C# yang dapat diakses melalui COM. Kelas ini adalah sebuah kelas kalkulator yang berisi fungsi penjumlahan angka. Contoh ini saya adaptasi dari beberapa referensi bagus yang ada di [1,2,3]. […]

  15. Thanks for all of the labor on this website. Gloria enjoys doing research and it’s really easy to understand why. Most of us notice all of the compelling ways you make powerful guidelines by means of this web site and even foster participation from the others about this matter plus our favorite simple princess has always been discovering a lot of things. Enjoy the remaining portion of the year. You’re the
    one performing a great job.

  16. Hey there! I know this is sort of off-topic however I had to ask.
    Does operating a well-established blog such as yours take a lot of work?
    I am completely new to writing a blog but I do write in my journal daily.
    I’d like to start a blog so I can share my experience and feelings online.
    Please let me know if you have any ideas or tips for brand new aspiring bloggers.

    Appreciate it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: