One way to achieve the above is to register the C # dll file with the Microsoft Windows registry using the regasm command. This EXE command is included with Visual Studios distributions. The following is an example of using the command:
regasm Nameof # DLL.dll / tlb: NameofC # DLL.tlb
Once you have registered it in the registry, you will need to install it in the global build cache (GAC) using the gacutil command. It is also included with Visual Studios distributions. The following is an example of using the command:
gacutil / i Nameof # DLL.dll
Once these steps are completed, your C ++ code will be able to find C # dll, assuming your DLL files are built similarly to the following:
[WITH#]
using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace MyNameSpace { /// <summary> /// Interface for C++ DLL. This exposes the functions used inside the dll /// Make sure the return types, function names, and argument types match the class /// </summary> [ComVisible(true)] [Guid("CBA208F2-E43B-4958-97C7-C24EA5A213DE")] public interface IMyClass { int Function1(); int Function2(); } [ClassInterface(ClassInterfaceType.None)] [Guid("579091E6-83A1-4aa5-89A7-F432AB2A57E3")] [ComVisible(true)] public class MyClass : IMyClass { public MyClass() { //Constructor } public int Function1() { //Do something in C
Wherever you see the used GUID, this is a randomly generated global identifier used to identify your C # code. This number can be randomly generated using the GUID creation tool provided by Visual Studios in the Tools and Create GUID menus. Select a registry format and click "New GUID". Then just click on the copy and paste it where the GUID should be (Uncheck the brackets!)
[C ++]
#include <windows.h> #include "stdafx.h" #include <cstdlib> #pragma warning (disable: 4278) #import <mscorlib.tlb> raw_interfaces_only #include <stdio.h> //This path needs to be valid at compile time. The file does not need to be there in runtime when using the DLL after compile. #import "C:\\...\\NameofC#DLL.tlb" no_namespace named_guids extern "C" _declspec(dllexport) int _Function1() { int result = 0; IMyClass *CSharpInterface = NULL; //Open interface to C# CoInitialize(NULL); HRESULT hr = CoCreateInstance(CLSID_MyClass, NULL, CLSCTX_INPROC_SERVER, IID_IMyClass, reinterpret_cast<void**>(&CSharpInterface)); //Call Function1 C# method result = CSharpInterface->Function1(); //Close interface CoUninitialize(); //Return result return result; }
The required TLB file at compile time can be generated using the tlbexp command, also included in visual studio. Command usage example:
tlbexp Nameof # DLL.dll
If you do not specify a path, the following path will be specified by default:
C: \ Program Files \ Microsoft Visual Studio 9.0 \ VC
In several places, you can mess this up, and the C # DLL call will fail.
Hello,
SeaMossDesign