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;
}
Posted by cppkid