2

我有一个 DLL Com 服务器,实际上只由一个旧的 Delphi exe 应用程序使用。

COM Server 是多年前(不是我)用 C++ ATL 编写的。它实现回调(事件 - 是否相同?) - 使用传出接口IConnectionPointImpl。类工厂是单例的(标有DECLARE_CLASSFACTORY_SINGLETON

现在要求这个 COM 服务器必须在多个客户端之间共享:Delphi 和 C#(.NET 2.0,VS2008)。我把它说成DllSurrogate现在我可以从多个 Delphi 客户端使用它,使用继承自的类TOleServer,覆盖GetServer始终使用的方法CoCreateInstance(因为GetActiveObject通常会失败)并且它正在工作。

现在我需要从 C# WinService 使用它,我不知道从哪里开始。我编写了一个使用 WinApi 的小 C# Hello-world,CoCreateInstance并且DllImport("ole32.dll")- 我能够从 COM 服务器连接到现有实例,但无法订阅事件。

这是VS导入的DLL META-DATA: 在此处输入图像描述

我不知道这是否是正确的方法。这是aproximative代码:

using System;
using System.Collections.Generic;
using System.Text;
using SWLMLib;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;


namespace TestSWLM
{
    [Flags]
    enum CLSCTX : uint
    {
        //... defines here CLSCTX
    }

    class Program
    {
        [DllImport("ole32.dll", EntryPoint = "CoCreateInstance", CallingConvention = CallingConvention.StdCall)]
        static extern UInt32 CoCreateInstance([In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid,
           IntPtr pUnkOuter, UInt32 dwClsContext, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
           [MarshalAs(UnmanagedType.IUnknown)] out object rReturnedComObject);

        public static void AboutExpireHandler(IFeature pFeature, int HoursRemained)
        {
            Console.WriteLine("AboutExpireHandler, pFeature = {0}", pFeature.Code);        
        }

        static void Main(string[] args)
        {
            try
            {
                SWLMLib.ISWMgr lintfSWLMgr = null;

                object instance = null;
                UInt32 dwRes = CoCreateInstance(new Guid("8EAAFAD7-73F8-403B-A53B-4400E16D8EDF"), IntPtr.Zero, (uint)CLSCTX.CLSCTX_LOCAL_SERVER,
                    new Guid("00000000-0000-0000-C000-000000000046"), out instance);
                SWLMLib.SWMgrClass lSWLMgr = null;
                unsafe
                {
                    lintfSWLMgr = (instance as SWLMLib.ISWMgr);
                    Type liType = instance.GetType();
                }

                if (lintfSWLMgr != null)
                {
                    IntPtr iuknw = Marshal.GetIUnknownForObject(lintfSWLMgr);

                    IntPtr ipointer = IntPtr.Zero;
                    Guid lICPCGuid = typeof(IConnectionPointContainer).GUID;
                    Guid lICPGuid = typeof(IConnectionPoint).GUID;
                    Guid lIEv = new Guid("{C13A9D38-4BB0-465B-BF4A-487F371A5538}");
                    IConnectionPoint lCP = null;
                    IConnectionPointContainer lCPC = null;
                    Int32 r = Marshal.QueryInterface(iuknw, ref lICPCGuid, out ipointer);
                    lCPC = (IConnectionPointContainer)Marshal.GetObjectForIUnknown(ipointer);
                    lCPC.FindConnectionPoint(ref lIEv, out lCP);
                    Int32 outID;
                    lCP.Advise(???, out outID); // HERE I don't know what to do further
                    lIEvEv.FeatureAboutToExpire += AboutExpireHandler;
                }
            }
            catch (Exception E)
            {
                Console.WriteLine(E.Message);
                throw;
            }

            Console.ReadLine();
        }
    }
}

欢迎任何建议、链接和诀窍。

4

2 回答 2

1

看来我成功地连接到并处理了 DLL (in-proc) Com Server 的事件。

  1. 我将 COM 服务器作为 DLL 代理(此处为 HowTo)。
  2. Delphi 客户端 - 形成我的 COM 包装类,继承自 TOleServer 类,我重写了 GetServer 方法:

function TSWMgr.GetServer: IUnknown; begin OleCheck(CoCreateInstance(ServerData^.ClassId, nil, CLSCTX_LOCAL_SERVER, IUnknown, Result)); end;

  1. C#(Hello-World Client)端(在咨询了一些类似这样的 HowTos 之后):

//使用SWLMLib;//使用 System.Runtime.InteropServices; //使用 System.Runtime.InteropServices.ComTypes;

[Flags]
enum ReturnCode : uint
{
    S_OK = 0, S_FALSE = 1, REGDB_E_CLASSNOTREG = 0x80040154, CLASS_E_NOAGGREGATION = 0x80040110, E_NOINTERFACE = 0x80004002, E_POINTER = 0x80004003
}

[Flags]
enum CLSCTX : uint
{
    CLSCTX_INPROC_SERVER = 0x1, CLSCTX_INPROC_HANDLER = 0x2, CLSCTX_LOCAL_SERVER = 0x4,
    //... //others
    CLSCTX_ALL = CLSCTX_SERVER | CLSCTX_INPROC_HANDLER
}

/// <summary>
/// Sink Class implementig COM Server outgoing interface SWLMLib.ISWMgrEvents 
/// </summary>
[ClassInterface(ClassInterfaceType.None)]
class MySink : SWLMLib.ISWMgrEvents
{
    public void FeatureAboutToExpire(SWLMLib.IFeature pFeature, int HoursRemained)
    {
        Console.WriteLine("{0} FeatureAboutToExpire: Feature {1} Hours={2}", DateTime.Now, pFeature.Code, HoursRemained);
        Marshal.ReleaseComObject(pFeature); //WTF??? Without this line COM Server object is not released!
    }

    public void FeatureExpired(SWLMLib.IFeature pFeature)
    {
        Console.WriteLine("FeatureExpired: Feature {0}", pFeature.Code);
        Marshal.ReleaseComObject(pFeature); //Without this line COM Server object is not released!
    }
}

class Program
{
    //Import "CoCreateInstance" to play with run context of created COM-object (3rd parameter)
    [DllImport("ole32.dll", EntryPoint = "CoCreateInstance", CallingConvention = CallingConvention.StdCall)]
    static extern UInt32 CoCreateInstance([In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid,
       IntPtr pUnkOuter, UInt32 dwClsContext, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
       [MarshalAs(UnmanagedType.IUnknown)] out object rReturnedComObject);

    static void Main(string[] args)
    {
        try
        {
            Guid SWMgrClassObjectGuid = typeof(SWLMLib.SWMgrClass).GUID;    //{8EAAFAD7-73F8-403B-A53B-4400E16D8EDF}
            Guid IUnknownGuid = new Guid("00000000-0000-0000-C000-000000000046"); //Can it be written in more pretty style?

            SWLMLib.ISWMgr lintfSWLMgr = null;

            /* This will create IN-PROC Server because, it seems CoCreateInstance will be invoked with CLSCTX_INPROC_SERVER flag settled
            Type type = Type.GetTypeFromCLSID(SWMgrClassObjectGuid), true);
            object instance0 = Activator.CreateInstance(type);
            lintfSWLMgr = (instance0 as SWLMLib.ISWMgr); */

            Guid Ev1 = typeof(ISWMgrEvents).GUID;
            object instance = null;

            unsafe
            {
                UInt32 dwRes = CoCreateInstance(SWMgrClassObjectGuid,
                                                IntPtr.Zero,
                                                (uint)(CLSCTX.CLSCTX_LOCAL_SERVER), //if OR with CLSCTX_INPROC_SERVER then INPROC Server will be created, because of DLL COM Server
                                                IUnknownGuid,
                                                out instance);
                if (dwRes != 0)
                {
                    int iError = Marshal.GetLastWin32Error();
                    Console.WriteLine("CoCreateInstance Error = {0}, LastWin32Error = {1}", dwRes, iError);
                    return;
                }
                lintfSWLMgr = (instance as SWLMLib.ISWMgr);
            }

            if (lintfSWLMgr != null)
            {
                //lintfSWLMgr.InitializeMethod(...); //Initialize object

                //Find Connection Point for Events
                Guid ISWMgrEventsGuid = typeof(SWLMLib.ISWMgrEvents).GUID;      //{C13A9D38-4BB0-465B-BF4A-487F371A5538} Interface for Evenets Handling
                IConnectionPoint lCP = null;
                IConnectionPointContainer lCPC = (instance as IConnectionPointContainer);
                lCPC.FindConnectionPoint(ref ISWMgrEventsGuid, out lCP);

                MySink lSink = new MySink();
                Int32 dwEventsCookie;
                lCP.Advise(lSink, out dwEventsCookie);
                Console.WriteLine("Waiting for Events Handling...");
                Console.WriteLine("Press ENTER to Exit...");

                Console.ReadLine(); // Until Eneter is not hit, the events arrive properly
                //Here starting to Unsubscribe for Events and Com Objects CleanUP
                lCP.Unadvise(dwEventsCookie);
                Marshal.ReleaseComObject(lCP); 
                Marshal.ReleaseComObject(lintfSWLMgr); 
            }

        }
        catch (Exception E)
        {
            Console.WriteLine(E.Message);
            throw;
        }
    }
}

也许这不是最好的方式(如 TblImp.exe 和/或 COM Wrappers),但这种原始方式有效。

于 2013-04-09T12:19:53.720 回答
0

我想你会想要编写如下代码:

Type type = Type.GetTypeFromCLSID(coClassGuid, true);
object instance = Activator.CreateInstance(type);

您可以认为这类似于CoCreateInstance.

C# COM Interop 的做法QueryInterface是进行强制转换或使用as关键字:

IComInterface comInterface = instance as IComInterface;

这将避免您必须直接使用 COM API。

我绝不是 COM 互操作专家,我只需要对它做一些工作,所以我希望这对您有所帮助。

于 2013-04-05T17:38:09.427 回答