Browse Archive

Newsletter

Please enter your e-mail address to subscribe to our newsletter.

Breaking news

Events

< February 2012 >
Mo Tu We Th Fr Sa Su
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29        

Access a .NET class library with Delphi through COM

2007-11-21 15:57 by Ronald Klaui

Accessing a .NET program (more specifically a class library) in Delphi can be done through a COM interface.
The following example demonstrates how you can communicate to a .NET library via Delphi:

In Visual Studio create a new C# project, a class library.


Copy the following code into the class1.cs file:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ClassLibrary1
{
[ComVisible(true)]
[Guid("D6F88E95-8A27-4ae6-B6DE-0542A0FC7039")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface _TestClass
{
[DispId(1)]
string GetName();

[DispId(2)]
void DoArray(String[] aByteArray);

[DispId(3)]
int GetNumber();
}

[ComVisible(true)]
[Guid("D5BA470D-AE18-46d3-BBD3-B476685D6142")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("ClassLibrary1.TestClass")]
public class TestClass : _TestClass
{
public TestClass()
{
}

public string GetName()
{
return "Donald Duck";
}

public int GetNumber()
{
return 55; // Donald Duck 55 !
}

public void DoArray(String[] aByteArray)
{
foreach (string s in aByteArray)
{
MessageBox.Show(s);
}
}
}

}

In order to get this to run properly you need to do the following:

  • Add a reference to the System.Windows.Forms.dll.
  • In the project properties (section: Configuration properties -> Build) enable the 'Register for COM interop' option.
  • Visual Studio 2005 users: You must also check the "make COM visible" option in the assembly information dialog (look hard). If this check is not set then you will not be able to access the COM Library through Delphi.

Build this project.

In Delphi, start a new project. Go to project | Import Type Library. Add the TLB file which just has been created while building the .NET class library to the project. (Don't forget to press the "create unit" button!)

Add 3 buttons (Button1, Button2 and Button3) to the project. Add the following code:

procedure TForm1.FormCreate(Sender: TObject);
begin
myInterface := TTestClass.Create(Self);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(myInterface.GetNumber));
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
ShowMessage(myInterface.GetName);
end;

procedure TForm1.Button3Click(Sender: TObject);
var
vArray : OleVariant;
begin
vArray := VarArrayCreate([0,4], varOleStr);
vArray[0] := 'Macaroni';
vArray[1] := 'with ';
vArray[2] := 'cheese';
vArray[3] := 'is';
vArray[4] := 'nice!';

myInterface.DoArray(vArray);
end;

This example should give a clear view on how to access a .NET class library via Delphi.

Go back

Add a comment