首页 > 解决方案 > 如何导出C#编写的接口实现TLB生成的Delphi代码

问题描述

我目前正在开发旧 COM 接口(用于与其他设备通信)的“插入式”替换。这个接口目前在一个大的应用程序中使用。旧的 COM 接口现在已被库的作者弃用,他们现在只支持和开发 C# 接口。我的任务是开发上述“插入式”替代品。它充当旧应用程序(用 Delphi 编写)和新的基于 C# 的接口之间的代理。我试图在主应用程序中进行尽可能少的代码更改。因此,我尝试尽可能好地模仿旧界面。所以我正在用 C# 编写代码,然后将其导出到 TLB 文件中。TLB 文件用于使用“TLIBIP.EXE -P”命令生成 Delphi 对应文件。

这是使用旧界面生成的代码。如您所见,有一个属性 Cat 可以使用索引调用它以获取其后面的集合的适当项目。

IDFoo = interface(IDispatch)
    ['{679F4D30-232F-11D3-B461-00A024BEC59F}']
    function Get_Cat(Index: Integer): IDFoo; safecall;
    procedure Set_Cat(Index: Integer; const Evn: IDFoo); safecall;
    property Cat[Index: Integer]: IDFoo read Get_Cat write Set_Cat;
end;

我正在尝试获取一个 C# 对应项,该对应项生成一个 TLB 文件,其中包含 Cat[index] 属性。

所以到目前为止我的解决方案是:C#:

[ComVisible(true)]
[Guid("821A3A07-598B-450D-A22B-AA4839999A18")]
public interface ICat
{
    ICat this[int index] { get; set; }
}

这会产生一个 TLB,然后产生这个 Delphi 代码:

  ICat = interface(IDispatch)
    ['{821A3A07-598B-450D-A22B-AA4839999A18}']
    function Get_Item(index: Integer): ICat; safecall;
    procedure _Set_Item(index: Integer; const pRetVal: ICat); safecall;
    property Item[index: Integer]: ICat read Get_Item write _Set_Item; default;
  end;

到目前为止,一切都很好。但是该属性被命名为“Item”,而不像原来的“Cat”。有没有人暗示我如何做到这一点?

标签: c#delphicomtlb

解决方案


Item是 C# 索引器的默认名称。

第一种可能性是在生成的 Delphi 代码中重命名Item为。Cat

第二种可能性是指定 C# 索引器名称:

[System.Runtime.CompilerServices.IndexerName("Cat")]
public ICat this[int index] { get; set; }

推荐阅读