Wednesday, February 6, 2013

Как да си напишем Service на .NET и да го ползваме в Delphi XE.

Using C# Library in Delphi XE


Как да си напишем Service на .NET и да го ползваме в Delphi XE


Ще започна с един прост пример "Hello World", който онагледява целия процес при изграждането на Dynamic-link library

1. Създайте нов проект в .NET  изберете class library.




















2. Изтрийте файла class1.cs
3. Създайте нов interface: ITest.cs























4. Създайте нов class : Test.cs

5. Добавете следния код в ITest.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace HelloWorld
{
public interface ITest
{
[ComVisible(true)]
string HelloWorld();
}
}


6.Добавете следния код в Test.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace HelloWorld
{
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Test : ITest
{
public Test()
{

}

[ComVisible(true)]
public string HelloWorld()
{
return "Hello World";
}
}
}

7.Отворете файла AssemblyInfo.cs и променете  [assembly: ComVisible(false)]
 на  [assembly: ComVisible(true)]


8.Компилирайте

9.Отворете с administrator command prompt на Visual Studio и регистрирайте вашата dll-ка














regasm [target path] /tlb:HelloWorld.tlb

Тarget path e пътя до вашата dll-ка пример:  (D:\Projects\HelloWorld\\HelloWorld\bin\Debug\HelloWorld.dll)


Използване на Dll в Delphi


1.Изберете Component - Import component - import type library.Изберете Next
2. Изберете (потърсете) HelloWorld от списъка - Изберете Next
3.Изберете отметка "Generate Component Wrappers"
4.Изберете отметка "Create Unit"

Създайте нов проект добавете в uses HelloWorld_TLB
Добавете файла създаден в .net HelloWorld.dll  в Debug\Win32

Ето и кода в Delphi


unit HelloWorld;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, HelloWorld_TLB, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    ftest: TTest;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  ftest := TTest.Create(nil);
  ShowMessage(ftest.HelloWorld);
end;

end.


Резултат



















Надявам се да съм бил полезен!





No comments:

Post a Comment