Monday, 1 February 2010

Using C# assembly from Delphi Win32

A hands-on lab on how to call a C# class from within delphi win32 code


1. First declare a C# interface as follows




    public interface IMyClass


        void DoSomething();



2. Write a class that implements the interface

    class MyClass : MarshalByRefObject, IMyClass


        public void DoSomething()






3. Make sure to set the assembly COM-Visible: Project options -> Application Tab -> Check “Make assembly COM visible”



4. Declare the same Interface also in delphi:


IMyClass = interface ['{1F3E8CE4-A8BF-47B3-A31E-A07BB3ECD192}']

  procedure DoSomething; safecall;



5. Create and use the class with the following code:

function ClrCreateManagedInstance(pTypeName: PWideChar; const riid: TIID; out ppObject): HRESULT; stdcall; external 'mscoree.dll';


procedure DoSomething;

var mc: IMyClass;

    hr: HRESULT;

    NetClassName: WideString;


    //Partial assembly name works but full assembly name is preffered.

    NetClassName := 'MyAssembly.MyClass, MyAssembly'; // 'Full type name, dllName'

    hr := ClrCreateManagedInstance(PWideChar(NetClassName), IMyClass, mc);






That’s all.

For more detailed info please visit the following links