以下是一个简单的C#自定义COM服务器示例,提供完整代码,可以通过GetObject获取对象:

using System; using System.Runtime.InteropServices;

namespace CustomCOMServer { [Guid("F3B7A5D5-5C5F-4C9A-9F1E-2D7C8C8D8B7B")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface ICustomCOMServer { [DispId(1)] string HelloWorld(); }

[Guid("C3F9C7E0-3FBD-4F1A-8A7C-6ED7B5B5B9B9")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(ICustomCOMServer))]
public class CustomCOMServer : ICustomCOMServer
{
    public string HelloWorld()
    {
        return "Hello World from Custom COM Server!";
    }
}

}

在此示例中,我们创建了一个名为CustomCOMServer的COM服务器,它实现了一个名为ICustomCOMServer的COM接口。该接口只有一个方法HelloWorld,它返回一个字符串“Hello World from Custom COM Server!”。

要将此COM服务器注册到系统中,可以使用以下命令:

regasm CustomCOMServer.dll /codebase

此命令将注册CustomCOMServer.dll并将其放置在全局程序集缓存中,以便其他应用程序可以使用它。

要在C#客户端应用程序中使用此COM服务器,可以使用以下代码:

using System; using System.Runtime.InteropServices;

namespace CustomCOMClient { class Program { static void Main(string[] args) { Type comType = Type.GetTypeFromProgID("CustomCOMServer.CustomCOMServer"); dynamic comObject = Activator.CreateInstance(comType);

        Console.WriteLine(comObject.HelloWorld());

        Marshal.ReleaseComObject(comObject);
    }
}

}

在此示例中,我们使用Type.GetTypeFromProgID方法获取COM服务器的类型,然后使用Activator.CreateInstance方法创建COM对象。我们可以调用HelloWorld方法并输出结果。最后,我们使用Marshal.ReleaseComObject方法释放COM对象。

要运行此示例,必须将CustomCOMServer.dll和CustomCOMClient.exe放置在同一目录中,并使用以下命令运行CustomCOMClient.exe:

CustomCOMClient.exe

此命令将输出“Hello World from Custom COM Server!”并退出应用程序。


原文地址: https://www.cveoy.top/t/topic/bIN3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录