Can somebody please post here an example how to host CLR in Delphi? I have read similar question here but I cannot use JCL as I want to host it in Delphi 5. Thank you.
Thanks this forum I find out the best solution to use dll C# with Lazarus:
C#:
using System;
using System.Collections.Generic;
using System.Text;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;
namespace DelphiNET
{
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BA7DFB53-6CEC-4ADA-BE5E-16F1A46DFAC5")]
public interface IDotNetAdder
{
int Add3(int left);
int Mult3(int left);
string Expr3(string palavra);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class DotNetAdder : DelphiNET.IDotNetAdder
{
public int Add3(int left)
{
return left + 3;
}
public int Mult3(int left)
{
return left * 3;
}
public string Expr3(string palavra)
{
return palavra + " é a palavra que estou esperando!";
}
}
internal static class UnmanagedExports
{
[DllExport("createdotnetadder", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
static void CreateDotNetAdderInstance([MarshalAs(UnmanagedType.Interface)]out IDotNetAdder instance)
{
instance = new DotNetAdder();
}
}
}
Lazarus:
unit uDLLC01;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls{, dynlibs};
type
IDotNetAdder = interface
['{BA7DFB53-6CEC-4ADA-BE5E-16F1A46DFAC5}']
function Add3(left : integer):integer; safecall; {stdcall nao funciona}
function Mult3(left : integer):integer; safecall;
function Expr3(left : WideString):WideString; safecall;
end;
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{stdcall e cdecl work well; cdecl say is C style to Lazarus}
procedure createdotnetadder(out instance:IDotNetAdder); cdecl external 'IDotNetAdder.dll' name 'createdotnetadder';
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
x : LongInt = 0;
y : LongInt = 0;
z : WideString;
nTam : integer;
adder : IDotNetAdder;
begin
try
createdotnetadder(adder);
z := adder.Expr3('Antonio');
nTam := Length(z);
x := adder.Add3(4);
y := adder.Mult3(4);
finally
showmessage('4 + 3 = '+ (inttostr(x)));
showmessage('4 * 3 = '+ (inttostr(y)));
showmessage('Expressão = ' + String(z));
end;
end;
end.
Observe that var Z is WideString, the only type that worked as string type, I tried String, AnsiString and PChar but didnt work, they return only the first char. Im having problem with accent like the word "Antônio" to send as parameter, Im trying to find a converter that the C# can understand and send back the same word.