Saturday 27 November 2010

Spam

A lot of spam in this period... so I've changed setting to allow comments for registered users only.
Sad.

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

 

    [Guid("1F3E8CE4-A8BF-47B3-A31E-A07BB3ECD192")]

    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]

    public interface IMyClass

    {

        void DoSomething();

    }

 

2. Write a class that implements the interface

    class MyClass : MarshalByRefObject, IMyClass

    {

        public void DoSomething()

        {

            System.Windows.Forms.MessageBox.Show("Hello!");

        }

    }

 

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:

type

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

  procedure DoSomething; safecall;

end;

 

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;

begin

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

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

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

    OleCheck(hr);

    mc.DoSomething();

end;

 

 

That’s all.

For more detailed info please visit the following links

http://interop.managed-vcl.com/netinterop_csharp.php

http://stackoverflow.com/questions/787303/how-to-use-net-assembly-from-win32-without-registration