Search code examples
c#delphidllcomdelphi-7

Call C# .Net DLL in delphi 7


Anyone know how can I create a C# dll which can be called in Delphi 7 program? I do that through the ComVisibleAttribute but delphi program takes error.

C# DLL Code (Class Library Project):

namespace MyTest
{
        [ComVisible(true)]
        [GuidAttribute("EF00685F-1C14-4D05-9EFA-538B3137D86C")]
        [ClassInterface(ClassInterfaceType.None)]
        public class MainTest
        {
                public int AddP(int value)
                {
                   return value + 314;
                } 
        }
}

Delphi 7 Main Program Code:

function AddP(Value: integer): integer; stdcall;
  external 'DelphiTest.dll';

procedure TfrmMain.btnConvertClick(Sender: TObject);
var value : double;
Begin
      Text := IntToStr(AddP(10000));
End;

It takes error:

The application was unable to start correctly (0xc000007b). Click OK to close the application.


Solution

  • My answer is not regarding Delphi, but about the general things. No exact solution, only links. Basically, you have several options to call managed code from unmanaged:

    Create COM object. You create c# dll and class with COM-related attributes MainTest. Then you register your dll in the system (using regasm.exe). As a result your Com-object can be consumed from any language including Delphi. Check this post out for more info

    Make a wrapper with Managed c++ (c++/cli) This is also a very popular technique. The thing is that c++/cli dlls can mix managed and unmanaged code. So you basically create unmanaged wrappers for managed code. Check this post out for more info

    Use IL hack. This facility would work for static methods only and it's more like a hack since you need to change IL code. This post describes it

    So you're basically trying to mix 1st and 3rd approaches. You need to stick to one. Personally I prefer second approach since it is easy to deploy and safe to use