有人可以在这里发布一个如何在 Delphi 中托管 CLR 的示例吗?我读过类似的question https://stackoverflow.com/questions/258875/hosting-the-net-runtime-in-a-delphi-program在这里,但我不能使用 JCL,因为我想在 Delphi 5 中托管它。谢谢。
EDIT: This article http://www.west-wind.com/Weblog/posts/104449.aspx关于在 Fox Pro 中托管 CLR 看起来很有希望,但我不知道如何从 Delphi 访问 clrhost.dll。
Edit 2:我放弃了 Delphi 5 的要求。现在我正在尝试使用 Delphi 7 的 JCL。但我再次找不到任何示例。这是我到目前为止所拥有的:
我的 C# 程序集:
namespace DelphiNET
{
public class NETAdder
{
public int Add3(int left)
{
return left + 3;
}
}
}
我已将其编译为DelphiNET.dll
.
现在我想使用 Delphi 中的这个程序集:
uses JclDotNet, mscorlib_TLB;
procedure TForm1.Button1Click(Sender: TObject);
var
clr: TJclClrHost;
ads: TJclClrAppDomainSetup;
ad: TJclClrAppDomain;
ass: TJclClrAssembly;
obj: _ObjectHandle;
ov: OleVariant;
begin
clr := TJclClrHost.Create();
clr.Start;
ads := clr.CreateDomainSetup;
ads.ApplicationBase := 'C:\Delhi.NET';
ads.ConfigurationFile := 'C:\Delhi.NET\my.config';
ad := clr.CreateAppDomain('myNET', ads);
obj := (ad as _AppDomain).CreateInstanceFrom('DelphiNET.dll', 'DelphiNET.NETAdder');
ov := obj.Unwrap;
Button1.Caption := 'done ' + string(ov.Add3(5));
end;
这以错误结束:EOleError:变体未引用自动化对象
我已经很长时间没有使用 Delphi 了,所以我被困在这里......
解决方案:COM 可见性存在问题,但默认情况下并非如此。这是正确的 .NET 程序集:
namespace DelphiNET
{
[ComVisible(true)]
public class NETAdder
{
public int Add3(int left)
{
return left + 3;
}
}
}
重要的提示:
当使用 Delphi 的 .NET 时,重要的是调用Set8087CW($133F);
在你的程序开始时(即之前Application.Initialize;
)。 Delphi 默认启用浮点异常(请参见this http://digital.ni.com/public.nsf/allkb/E6A73825E57FCD9F862570DD005E594F)并且 CLR 不喜欢它们。当我启用它们时,我的程序奇怪地冻结了。