【发布时间】:2023-03-19 05:39:01
【问题描述】:
能否告诉我.NET 组件是否可以与 Delphi 2009 一起使用,如果可以,请给我一些示例代码。
提前致谢。
【问题讨论】:
标签: .net delphi components delphi-2009
能否告诉我.NET 组件是否可以与 Delphi 2009 一起使用,如果可以,请给我一些示例代码。
提前致谢。
【问题讨论】:
标签: .net delphi components delphi-2009
是的,可以在 win32 程序中使用 .net 组件。不幸的是,自己做起来并不简单,我强烈推荐Hydra。
【讨论】:
有几种方法可以做到这一点,传统的 COM/Interop 只是其中一种方法。
另一种方法是使用 CLR 中内置的现有基础架构来支持 COM/Interop 和混合模式 C++/CLI。
你很幸运,我已经在另一个论坛上回答了一个非常相似的问题。所以我已经有了一些示例代码。 ;-)
我在这里展示的可能不是你的那杯茶。
归根结底,我自己不会使用经典 COM。除非它真的有意义。 (就像为 Office 编写 COM-Addins)
在 VisualStudio 中,您可以使用重构/提取接口向导从您的组件中获取具有您需要的方法的接口。
你需要提供这3个属性
[ComVisible(true)]
[Guid("Create a GUID yourself"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IYourInterface
为了简单起见,我假设你的组件只有一个简单的方法。 在 VisualStudio 中创建一个类库,然后按照其他页面中的步骤进行操作。 (为了能够导出函数)
[ComVisible(true)]
[Guid("Create a GUID yourself"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IYourInterface
{
void DoSomething(int value);
}
public class YourComponent : IYourInterface
{
public void DoSomething(int value)
{
return value + 1;
}
}
static class Exports
{
[DllExport("createyourcomponent")]
public static void CreateInstance([MarshalAs(UnmanagedType.Interface)]out IYourInterface instance)
{
instance = new YourComponent();
}
}
在 Delphi 中,您可以根据需要将此接口包装在组件中。 这将隐藏涉及 .Net 的事实:
type
IYourInterface = interface
['{Create a GUID yourself}']//Control+Shift+G in Delphi
// important, safecall is used by COM/Interop
procedure DoSomething(aValue : Integer); safecall;
end;
TYourComponent = class(TComponent)
private
fInnerInstance : IYourInterface;
public
procedure DoSomething(aValue : Integer);
constructor Create(aOwner : TComponent);
end;
implementation
procedure CreateManagedInstance(out aInstance : IYourInterface);
stdcall; external 'YourDotNetLibraryName'
name 'createyourcomponent';
constructor TYourComponent.Create(aOwner : TComponent);
begin
inherited Create(aOwner);
CreateManagedInstance(fInnerInstance);
end;
procedure TYourComponent.DoSomething(aValue : Integer);
begin
fInnerInstance.DoSomething(aValue);
end;
免责声明:我手边没有 IDE,因此示例代码中可能存在拼写错误或其他错误...
【讨论】:
您可以将 .NET 组件与作为 RAD 工作室的一部分的 Delphi for .NET 一起使用
【讨论】: