从 64 位 c# WinForms 应用程序调用第三方 32 位 dll 时的事件处理

Event handling at calling a third party 32-bit dll from a 64-bit c# WinForms application

我们有一个旧的 32 位 Visual Studio C# Windows Forms 解决方案,我们希望从现在开始以 64 位编译它。不幸的是,我们的应用程序使用了一些仅在 32 位版本中可用的外部 dll-s(用于扫描仪、相机等)。 Accessing 32-bit DLLs from 64-bit code 并不简单,尤其是当我们还想处理那些 dll-s 引发的事件时。我们在这方面的知识不足以创建基于本文的实现,因此我们正在寻找更详细的说明或示例。

我们的第一次尝试是基于 this article。我们将第三方 dll-s 包装到后期绑定的 32 位 COM 服务器中,并从我们的 64 位应用程序中使用它,如此处所述(必要的修正,因为我们必须交换 32 位和 64 位的角色) .此尝试成功但不完整,因为此解决方案不会将事件从 COM 服务器传递到 64 位客户端。所以我们开始关注事件。我们找到了很多处理 COM 对象引发的消费事件的文章和示例,但其中 none 为我们提供了完整的解决方案。一部分源专门处理客户端,或专门处理服务器,但它们彼此不兼容,或与我们的环境(WinForm、c#)不兼容。

例如,

  1. 告诉我们如何制作一个将 .NET 事件暴露给 VB 客户端的 COM 服务器,但我不知道如何从 c# 客户端使用它。
  2. 相比之下,this article 为现有的 COM 服务器提供了一个运行良好的 c# 客户端,但没有说明如何制作这样的 COM 服务器(这个 COM 服务器明显不同于前面的示例)
  3. this answer 没有说明解决方案的任何细节。
  4. This article 适用于 c++ 而不是 c#。
  5. This answer refers to this article,但后者再次使用 VB 客户端而不是 c#。
  6. This article 以无法追踪的方式混合不同的东西。

也许我们可以通过一些努力使用其中的一些,但是使用哪些以及如何使用?

编辑

现在我倾向于创建一个混合解决方案:对于从 32 位 COM 对象到调用者 64 位应用程序的反向通信,我的最新想法是将一个命名管道服务器放入 64 位应用程序中,然后将一个命名管道客户端进入 COM 对象,每次在 COM 对象中引发事件时,它都会向命名管道服务器发送一条命名管道消息。我为此找到的代码可用 here(项目 CSNamedPipeServer 和 CSNamedPipeClient)。

这是一个带有 64 位服务器的示例,在 class 库项目中作为 C# class 实现,由 Windows' 系统代理托管:dllhost。

这是class代码(可以编译为'any cpu',不需要编译为x64):

namespace NetComClassLibrary3
{
    // technically, we don't *have to* define an interface, we could do everything using dynamic stuff
    // but it's more practical so we can reference this .NET dll from our client
    [ComVisible(true)]
    [Guid("31dd1263-0002-4071-aa4a-d226a55116bd")]
    public interface IMyClass
    {
        event OnMyEventDelegate OnMyEvent;
        object MyMethod();
    }

    // same remark than above.
    // This *must* match the OnMyEvent signature below
    [ComVisible(true)]
    [Guid("31dd1263-0003-4071-aa4a-d226a55116bd")]
    public delegate void OnMyEventDelegate(string text);

    // this "event" interface is mandatory
    // note from the .NET perspective, no one seems to implement it
    // but it's referenced with the ComSourceInterfaces attribute on our COM server (below)
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    [Guid("31dd1263-0000-4071-aa4a-d226a55116bd")]
    public interface IMyEvents
    {
        // dispids are mandatory here otherwise you'll get a DISP_E_UNKNOWNNAME error
        [DispId(1)]
        void OnMyEvent(string text);
    }

    [ComVisible(true)]
    [ComSourceInterfaces(typeof(IMyEvents))]
    [Guid("31dd1263-0001-4071-aa4a-d226a55116bd")]
    public class MyClass : IMyClass
    {
        public event OnMyEventDelegate OnMyEvent;

        public object MyMethod()
        {
            // we use the current running process to test out stuff
            // this should be Windows' default surrogate: dllhost.exe
            var process = Process.GetCurrentProcess();
            var text = "MyMethod. Bitness: " + IntPtr.Size + " Pid: " + process.Id + " Name: " + process.ProcessName;
            Console.WriteLine(text); // should not be displayed when running under dllhost
            OnMyEvent?.Invoke("MyEvent. " + text);
            return text;
        }
    }
}

这是我注册它的方式(注意我的目标是 64 位注册表):

%windir%\Microsoft.NET\Framework64\v4.0.30319\regasm.exe NetComClassLibrary3.dll /codebase /tlb

这是一个 .reg 以确保它 运行 在 dllhost.exe 中处于进程外(guid 是 COM coclass MyClass 的 guid):

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\AppID\{31dd1263-0001-4071-aa4a-d226a55116bd}]
"DllSurrogate"=""

[HKEY_CLASSES_ROOT\CLSID\{31dd1263-0001-4071-aa4a-d226a55116bd}]
"AppID"="{31dd1263-0001-4071-aa4a-d226a55116bd}"

这是编译为 x86 的客户端:

using System;
using NetComClassLibrary3; // we can reference the .net dll as is

namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Bitness: " + IntPtr.Size);
            // note we don't use new MyClass() otherwise we may go inprocess
            var type = Type.GetTypeFromCLSID(typeof(MyClass).GUID);
            var obj = (IMyClass)Activator.CreateInstance(type);

            // note I'm using the beloved dynamic keyword here. for some reason obj.OnMyEvent works but locally raises a cast error I've not investigated further...
            dynamic d = obj;
            d.OnMyEvent += (OnMyEventDelegate)((t) =>
            {
                Console.WriteLine(t);
            });
            Console.WriteLine(obj.MyMethod());
        }
    }
}

当我运行它时,这是输出:

Bitness: 4 // running as 32-bit
MyEvent. MyMethod. Bitness: 8 Pid: 23780 Name: dllhost // from 64-bit world
MyMethod. Bitness: 8 Pid: 23780 Name: dllhost // from 64-bit world

当我们在 Simon Mourier 的解决方案中交换 32 位和 64 位的角色时,那么 - 除了改变编译位数 - 我们应该改变 4 件事。

(1) 更改注册

来自

%windir%\Microsoft.NET\Framework64\v4.0.30319\regasm.exe NetComClassLibrary3.dll /codebase /tlb

%windir%\Microsoft.NET\Framework\v4.0.30319\regasm.exe NetComClassLibrary3.dll /codebase /tlb

(2) 更改注册表项

来自

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\AppID\{31dd1263-0001-4071-aa4a-d226a55116bd}]
"DllSurrogate"=""

[HKEY_CLASSES_ROOT\CLSID\{31dd1263-0001-4071-aa4a-d226a55116bd}]
"AppID"="{31dd1263-0001-4071-aa4a-d226a55116bd}"

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\AppID\{31dd1263-0001-4071-aa4a-d226a55116bd}]
"DllSurrogate"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\CLSID\{31dd1263-0001-4071-aa4a-d226a55116bd}]
"AppID"="{31dd1263-0001-4071-aa4a-d226a55116bd}"

(3) 在64位客户端中,不要注册32位的NetComClassLibrary3.dll,而是将IMyClassOnMyEventDelegate的定义复制到客户端源代码

(4) 同样在客户端,

改变

var type = Type.GetTypeFromCLSID(typeof(MyClass).GUID);

var type = Type.GetTypeFromProgID("NetComClassLibrary3.MyClass");

所以客户看起来是这样的:

using System;
// removed by mma - using NetComClassLibrary3; // we can reference the .net dll as is

namespace ConsoleApp10
{
    // inserted by mma:
    [System.Runtime.InteropServices.Guid("31dd1263-0002-4071-aa4a-d226a55116bd")]
    public interface IMyClass
    {
        event OnMyEventDelegate OnMyEvent;
        object MyMethod();
    }
    [System.Runtime.InteropServices.Guid("31dd1263-0002-4071-aa4a-d226a55116bd")]
    public delegate void OnMyEventDelegate(string text);
    // end of insertion

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Bitness: " + IntPtr.Size);
            // note we don't use new MyClass() otherwise we may go inprocess
            // removed by mma var type = Type.GetTypeFromCLSID(typeof(MyClass).GUID);
            // inserted by mma:
            var type = Type.GetTypeFromProgID("NetComClassLibrary3.MyClass");
            // end of insertion
            var obj = (IMyClass)Activator.CreateInstance(type);

            // note I'm using the beloved dynamic keyword here. for some reason obj.OnMyEvent works but locally raises a cast error I've not investigated further...
            dynamic d = obj;
            d.OnMyEvent += (OnMyEventDelegate)((t) =>
            {
                Console.WriteLine(t);
            });
            Console.WriteLine(obj.MyMethod());
        }
    }
}

所以输出将从

Bitness: 4 // running as 32-bit
MyEvent. MyMethod. Bitness: 8 Pid: 23780 Name: dllhost // from 64-bit world
MyMethod. Bitness: 8 Pid: 23780 Name: dllhost // from 64-bit world

Bitness: 8 // running as 64-bit
MyEvent. MyMethod. Bitness: 4 Pid: 56140 Name: dllhost // from 32-bit world
MyMethod. Bitness: 4 Pid: 56140 Name: dllhost // from 32-bit world

备注IMyClassOnMyEventDelegate 的定义添加到客户端的源代码中而不是注册 32 位 NetComClassLibrary3.dll 也适用于 32 位客户端 + 64 位 COM 服务器版本,但是在 64 位客户端中引用 32 位 COM dll 会导致 BadImageFormat 异常。