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;
}
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.
Sure.
Please keep watching the blog.
Thanks.
Очень интересно!!! Только не очень могу понять как часто обновляется ваш блог?
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 ?
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.
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.
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.
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.
lol, this sample was taken from Microsoft KB: http://support.microsoft.com/kb/828736
IAddClassPtr is not defined.
I have no clue of all this… would it be possible to explain it an even more “idiot proof” way?
Chor
where is IAddClassPtr declared? someone can explain this please.
he can’t explain ‘cos this is a CRP ( copy, Replace variable names ,paste ) article.
“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
[…] 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]. […]