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:
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.
Add a comment