You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8组件暴露给COM并在Delphi中调用的问题排查

.NET 8组件暴露给COM并在Delphi中调用的问题排查

参考微软文档《Expose .NET Core components to COM》,尝试将.NET 8组件暴露给COM以在Delphi中调用,操作及问题如下:

实现代码与配置

.NET 8代码

[ComVisible(true)]
[Guid("2D4D3084-E08E-469A-8442-6B3857C84AB9")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServer
{
    double ComputePi();
}

[ComVisible(true)]
[Guid("56986172-C929-44E5-8B67-41B97B7412D8")]
public class Server : IServer
{
    public double ComputePi()
    {
        return Math.PI;
    }
}

项目配置(.csproj)

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableComHosting>true</EnableComHosting>
  </PropertyGroup>

</Project>

注册COM宿主

执行命令:

regsvr32 Netphi.comhost.dll

手动编写IDL文件

[
    uuid(10E262F3-F715-4FA2-A63F-E3ED64134F49),
]
library Netphi
{
    importlib("stdole2.tlb");

    [
        uuid(2D4D3084-E08E-469A-8442-6B3857C84AB9),
    ]
    interface IServer : IUnknown
    {
        [id(1)]
        double ComputePi();
    };

    [
        uuid(56986172-C929-44E5-8B67-41B97B7412D8),
    ]
    coclass Server
    {
        [default] interface IServer;
    };
};

Delphi调用代码

执行midl命令生成.tlb文件并导入Delphi,自动生成包装器代码后,调用代码如下:

procedure TForm1.Button1Click(Sender: TObject);
var
  pServer : TServer;
begin
  pServer := TServer.Create(Self);
  pServer.ComputePi();
end;

问题排查过程

初始错误

运行Delphi代码时出现错误:

Class not registered, ClassID: {56986172-C929-44E5-8B67-41B97B7412D8}.

已确认该CLSID存在于HKEY_CLASSES_ROOT\CLSID注册表项中。

编辑1:32位版本适配错误

因Delphi应用为32位,执行命令发布32位版本:

dotnet publish -r win-x86 -c Release

将发布文件复制到C:/Windows/SysWoW64/,以管理员权限执行注册命令:

C:\Windows\SysWoW64\regsvr32.exe C:\Windows\SysWoW64\Netphi.comhost.dll

出现错误:

The module C:\WINDOWS\syswow64\Netphi.comhost.dll was loaded, but the call to DllRegisterService was terminated with the error code: 0x80008096.

编辑2:SDK安装后仍有异常

发现未安装32位.NET 8 SDK,安装后注册成功,但Delphi运行仍存在异常,计划使用dscom工具生成更准确的.tlb文件。


内容的提问来源于stack exchange,提问作者Maik Hasler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 11:45:56