C# COM 服务器到 C# COM 客户端使用 CoCreateInstance

标签 c# .net dll com

我需要创建一个 C# COM 服务器和一个 C# COM 客户端,并使用 CoCreateInstance 在两者之间进行通信。

这样客户端可以是 64 位的,服务器可以是 32 位的,使用 Hosting a .NET DLL as an Out-Of-Process COM Server (EXE) 中描述的“DllSurrogate”方法。 .

但是,目前我都有 32 位版本,但正在努力让它工作。

有创建 C# COM 服务器的在线示例:COM Interop Part 2: C# Server Tutorial

并创建一个 C# COM 客户端:COM Interop Part 1: C# Client Tutorial

但我还没有找到同时执行这两种操作的示例。 到目前为止,我的尝试都失败了,我怀疑用于 C# COM 客户端示例的 Microsoft COM 服务器包含 C# COM 服务器示例中没有的额外规范。

我目前的尝试如下。
C# 客户端对 CoCreateInstance 的调用显然是成功的,但返回的对象似乎是空的(不是 null),并且尝试将其转换为接口(interface)失败。

任何人都可以发现问题,或提供一个完全结合的例子吗?

这是我的服务器代码:

// AntCsServer.cs
// Project settings:
    // compile as a library
    // Select 'Make assembly COM Visible'
    // Select 'Register for COM Interop'

using System;
using System.Runtime.InteropServices;
namespace AntCsServer
{
    // Since the .NET Framework interface and coclass have to behave as 
    // COM objects, we have to give them guids.
    [Guid("555E2D2B-EE00-47AA-AB2B-39F953F6B339")]
    public interface IManagedInterface
    {
        int PrintHi(string name);
    }

    [Guid("0190D7A6-8D8D-4031-810A-627BA3EE68A6")]
    public class InterfaceImplementation : IManagedInterface
    {
        public int PrintHi(string name)
        {
            Console.WriteLine("Hello, {0}!", name);
            return 33;
        }
    }
}

这是我的客户端代码:

using System;
using System.Runtime.InteropServices;

namespace ComClient
{
    class Program
    {
        public const string ComSvrInterface_GUID = "555E2D2B-EE00-47AA-AB2B-39F953F6B339";
        public const string ComSvrClass_GUID = "0190D7A6-8D8D-4031-810A-627BA3EE68A6";

        [STAThread]
        static void Main(string[] args)
        {
            Ole32Methods.CoInitialize((IntPtr)0);

            object instance1 = null;
            string sErr1;
            bool b1;
            IManagedInterface cCom = null;

            b1 = Ole32Methods.CreateComObject(ComSvrClass_GUID, ComSvrInterface_GUID, out instance1, out sErr1);

            if (b1)
            {
                cCom = instance1 as IManagedInterface;
            }

            if (cCom != null)
            {
                cCom.PrintHi("Santa Claus");
                Console.WriteLine("Should have just printed Santa Claus");
            }

        }
    }

    // -------------------------------------------

    // Reproduce the interface here so we can cast to it
    [Guid("555E2D2B-EE00-47AA-AB2B-39F953F6B339")]
    public interface IManagedInterface
    {
        int PrintHi(string name);
    }

    // -------------------------------------------

    public class Ole32Methods
    {
        [DllImport("ole32.Dll")]
        static public extern uint CoCreateInstance(ref Guid clsid,
           [MarshalAs(UnmanagedType.IUnknown)] object inner,
           uint context,
           ref Guid uuid,
           [MarshalAs(UnmanagedType.IUnknown)] out object rReturnedComObject);

        [DllImport("ole32.dll")]
        public static extern int CoInitialize(IntPtr pvReserved);

        // ------------------------

        public static bool CreateComObject(string sClassGuid, string sInterfaceGuid, out object instance, out string sErr)
        {
            const uint CLSCTX_INPROC_SERVER = 1;
            //const uint CLSCTX_LOCAL_SERVER = 4;

            // CLSID of the COM object
            Guid clsid = new Guid(sClassGuid);

            // GUID of the required interface
            //Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
            Guid IID_Interface = new Guid(sInterfaceGuid);

            instance = null;

            uint hResult = Ole32Methods.CoCreateInstance(ref clsid, null,
                           CLSCTX_INPROC_SERVER, ref IID_Interface, out instance);


            // Some error codes. See 'winerror.h for more, and use the following to convert the debug value to Hex: http://www.rapidtables.com/convert/number/decimal-to-hex.htm

            const uint S_OK = 0x00000000;       //Operation successful
            const uint E_NOTIMPL = 0x80004001;       //Not implemented
            const uint E_NOINTERFACE = 0x80004002;       //No such interface supported
            const uint E_POINTER = 0x80004003;       //Pointer that is not valid
            const uint E_ABORT = 0x80004004;       //Operation aborted
            const uint E_FAIL = 0x80004005;       //Unspecified failure
            const uint E_UNEXPECTED = 0x8000FFFF;       //Unexpected failure
            const uint E_ACCESSDENIED = 0x80070005;       //General access denied error
            const uint E_HANDLE = 0x80070006;       //Handle that is not valid
            const uint E_OUTOFMEMORY = 0x8007000E;       //Failed to allocate necessary memory
            const uint E_INVALIDARG = 0x80070057;       //One or more arguments are not valid

            const uint E_CLASSNOTREG = 0x80040154;      // Class not registered

            sErr = "";
            switch (hResult)
            {
                case S_OK:
                    sErr = "";
                    break;
                case E_NOTIMPL:
                    sErr = "E_NOTIMPL: Not implemented";
                    break;
                case E_NOINTERFACE:
                    sErr = "E_NOINTERFACE: No such interface supported";
                    break;
                case E_POINTER:
                    sErr = "E_POINTER: Pointer that is not valid";
                    break;
                case E_ABORT:
                    sErr = "E_ABORT: Operation aborted";
                    break;
                case E_FAIL:
                    sErr = "E_FAIL: Unspecified failure";
                    break;
                case E_UNEXPECTED:
                    sErr = "E_UNEXPECTED: Unexpected failure";
                    break;
                case E_ACCESSDENIED:
                    sErr = "E_ACCESSDENIED: General access denied error";
                    break;
                case E_HANDLE:
                    sErr = "E_HANDLE: Handle that is not valid";
                    break;
                case E_OUTOFMEMORY:
                    sErr = "E_OUTOFMEMORY: Failed to allocate necessary memory";
                    break;
                case E_INVALIDARG:
                    sErr = "E_INVALIDARG: One or more arguments are not valid";
                    break;

                case E_CLASSNOTREG:
                    sErr = "E_CLASSNOTREG: Class not registered";
                    break;
            }

            return hResult == 0;

        }

    }
}

最佳答案

您正在加载进程中的 COM 服务器。这会导致 CLR 在进程中加载​​您的程序集,因此它使用标准程序集加载来加载它。您从 CoCreateInstance 获得的结果对象是文字 AntCsServer.InterfaceImplementation 类,它在服务器 DLL 中实现接口(interface),而不是在客户端 EXE 中实现接口(interface)。

这可以通过检查从 CoCreateInstance 返回的对象的类型来确认。如果它是 System.__ComObject,您将获得一个真正的 COM 对象(.NET 对象的代理对象)。如果不是,那么问题就是我所描述的——您实际上得到的是程序集类型的一个实例。

关于C# COM 服务器到 C# COM 客户端使用 CoCreateInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43229302/

相关文章:

c# - 处置流时如何处置任意依赖项?

c# - 如何在 C# 中对字符串进行切片?

.net - .Net在哪里可以找到BinaryFormatter序列化格式的官方规范?

c# - 从 vb.net 调用 WCF 时如何增加 MaxReceivedMessageSize

python - 尝试将 .dll 加载到 Python 时出错 "The specified module could not be found"

c# - DataGridView 数据绑定(bind)

c# - 将动态创建的菜单项从 Button.ContextMenu 绑定(bind)到 ICommand

c# - 如何在 C# 中通过 shell 执行文件?

dll - 如何在 D 中导入 COM dll

c# - 带有奇怪字符的Visual Studio错误