Today I had to create a C# Dll to be called from a Delphi 4 application. The only way of doing it is to register the Dll for COM interop. Its not that hard to do, but I was missing a few attributes on the class and the interface.
A few things are needed to start off:
- All needed Classes, Interfaces and Methods need to be public
- Assembly needs to be signed with a Strong Name
- Classes and Interfaces needs to have Guid’s
Easiest way to do it is to add all the needed methods to an interface and make your class implement the interface.
Guid’s are generated by:
guidgen.exe
The Interface:
// IRandom.cs using System.Runtime.InteropServices; [Guid("Axxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"), ComVisible(true)] public interface IRandom { [DispId(1), ComVisible(true)] int GetRandomNumber(int seed); // next methods get DispId(2), DispId(3), etc... }
The Class:
// RandomDll.cs using System.Runtime.InteropServices; [Guid("Bxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"), ClassInterface(ClassInterfaceType.None), ComVisible(true)] public class RandomDll: IRandom { #region IRandom Members [ComVisible(true)] public int GetRandomNumber(int seed) { Random rand = new Random(seed); returnĀ rand.Next(); } #endregion }
Sign the Assembly by generating a new key pair and adding it to the project. Next, click Properties on the project, go to the “Signing” tab and tick “Sign the assembly”. Then select the new key file with you generate.
Generate a key file:
sn.exe -k KeyPair.key
Last but not least, you’ll have to click Properties on the project, go to the “Build” tab and tick “Register for COM interop”. Now when you build, Visual Studio will export the type library for the Dll and register it as a COM object for you.
Now to use this Dll in Delphi you need to import the type library. Click Project->Import Type Library, select your .tlb and click Create Unit. Add the generated unit and ComObj to your uses list and reference the class via the interface.
uses ComObj; procedure TForm1.Button1Click(Sender: TObject) var interfaceRef: IRandom; result: Integer; begin interfaceRef := CreateComObject(CLASS_RandomDll_TLB) as IRandom; result := interfaceRef.GetRandomNumber(10); label1.Caption := IntToStr(result); end;
If all went well you’ll be able to call managed code from Delphi now!
The best and simple explanation of C# dll for Delphi which I find in Internet. Thank you for good job.