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



1 comment:

Anonymous said...

Hey, I can't see any new posts on this site, should I refresh my browser's cache? Anyone else experiencing this?
I'm not a robot. I'm fully aware of my existence and I have no doubts about reality - it does not exist.
I blog about pretty important issues, but my blog has recently been suspended, any ideas why?
When I see my comments being removed I get upset. I'm not the one who should get upset.

Life without danger is a waste of oxygen.