c# - 当我更改 C# COM dll 的签名时,为什么我必须从 x86 到 msil 再回到 x86

标签 c# c++ visual-studio com

我正在尝试让 C# 库通过 COM 将其类/方法公开给 native C++ 应用程序。我正在使用免注册 com(即使用 list 文件),以便不必向 Windows 注册 COM 库。我遇到了一个问题,如果我修改 C# 库并执行诸如添加新类或更改类的名称之类的操作,那么当在 C++ 应用程序中实例化该类时,它会引发 EETypeLoadException,我的理解意味着 COM库与 C++ 应用程序认为的外观不匹配。我的项目设置为每次构建时自动为 C# 库生成类型库和 list 文件,以便 C++ 应用程序获得最新版本。要修复此错误,我必须修改 C++ 应用程序的 list 文件,以说明 C# dll 以 msil 为目标,构建,然后将其翻转回 x86 并再次构建。此时 C++ 程序和 C# 程序是同步的并且不会抛出任何错误。我尝试清除输出目录和 obj 目录以删除任何可能的缓存文件,但这不起作用,只能来回切换 list 文件。

这是我的解决方案设置方式:

创建一个新的解决方案并向其中添加一个名为 ExampleLib 的 C# 类库 (.Net Framework)。

添加一个包含任意方法的接口(interface):

namespace ExampleLib
{
    public interface ITestClass
    {
        int Add(int a, int b);
    }
}

添加一个具有 guid 属性的类,该属性使用该接口(interface)并实现所需的方法。
using System.Runtime.InteropServices;

namespace ExampleLib
{
    [Guid("5054A38A-946A-4BB2-854B-E1A31633DD77")]
    public class TestClass : ITestClass
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
}

进入项目属性。在 Application 部分中单击 Assembly Information 并选中 Make assembly COM-Visible 框。在 Build 部分将平台目标设置为 x86 并将输出路径更改为:
..\Debug\

在 Build Events 部分中,将以下内容添加到 Post-build 事件中:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.2 Tools\tlbexp.exe" "$(TargetPath)" /out:"$(TargetDir)$(TargetName).tlb"
"C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x86\mt.exe" -managedassemblyname:"$(TargetPath)" -out:"$(TargetName).manifest" -nodependency

如果您安装了不同版本的 Windows SDK 或安装到不同位置,则需要更改上述命令以匹配 tblexp.exe 和 mt.exe 的位置。

将 C++ 控制台应用程序添加到名为 ExampleClient 的项目中。

在 Source Files 部分添加一个带有以下代码的 stdafx.cpp 文件(这是样板文件):
#include "stdafx.h"

在 ExampleClient.cpp 文件中,将模板中的默认代码替换为以下内容:
#include "stdafx.h"
#include "atlbase.h"
#include <conio.h>

#ifdef DEBUG
#import "..\Debug\ExampleLib.tlb" raw_interfaces_only
#else
#import "..\Release\ExampleLib.tlb" raw_interfaces_only
#endif

using namespace ExampleLib;

int main()
{
    HRESULT coInitResult = CoInitialize(0);
    try
    {
        ITestClassPtr pTest(__uuidof(TestClass));
    }
    catch (_com_error _com_err)
    {
        wprintf(L"\n %s", _com_err.ErrorMessage());
        auto _ = _getch();
    }
    CoUninitialize();
    return 0;
}

同样在 Source Files 部分添加 ExampleClient.exe.manifest 文件,其中包含以下内容:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity type="win32"
                    name="ExampleClient"
                    version="1.0.0.0">
  </assemblyIdentity>

  <dependency>
    <dependentAssembly>
      <assemblyIdentity name="ExampleLib" version="1.0.0.0" processorArchitecture="x86"/>
    </dependentAssembly>
  </dependency>
</assembly>

在 Header Files 部分添加一个 stdafx.h 文件(样板文件):
#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

同样在 Header Files 部分添加一个 targetver.h 文件(样板文件):
#pragma once
#include <SDKDDKVer.h>

右键单击 C++ 项目并卸载项目,然后编辑 ExampleClient.vcxproj 文件。与当前开箱即用的文件相比,此文件有许多更改,包括预编译头更改、不嵌入 list 、附加包含目录以及将 list 复制到输出目录。为了使复制更简单,我将只包含应该可以正常工作的整个文件
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|x64">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|x64">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <VCProjectVersion>16.0</VCProjectVersion>
    <ProjectGuid>{32A23FFD-3FD3-4191-8799-3A8DD34DCB94}</ProjectGuid>
    <Keyword>Win32Proj</Keyword>
    <RootNamespace>ExampleClient</RootNamespace>
    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="Shared">
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LinkIncremental>true</LinkIncremental>
    <EmbedManifest>false</EmbedManifest>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <LinkIncremental>true</LinkIncremental>
    <GenerateManifest>false</GenerateManifest>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LinkIncremental>false</LinkIncremental>
    <EmbedManifest>false</EmbedManifest>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <ClCompile>
      <PrecompiledHeader>Use</PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <AdditionalIncludeDirectories>..\$(Configuration)</AdditionalIncludeDirectories>
      <AdditionalUsingDirectories>
      </AdditionalUsingDirectories>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
    </Link>
    <PostBuildEvent>
      <Command>xcopy $(ProjectName).exe.manifest ..\$(Configuration)\ /Y</Command>
    </PostBuildEvent>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <ClCompile>
      <PrecompiledHeader>Use</PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <AdditionalIncludeDirectories>..\$(Configuration)</AdditionalIncludeDirectories>
      <AdditionalUsingDirectories>
      </AdditionalUsingDirectories>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
    </Link>
    <PostBuildEvent>
      <Command>
      </Command>
    </PostBuildEvent>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>Use</PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
    </Link>
    <PostBuildEvent>
      <Command>xcopy $(ProjectName).exe.manifest ..\$(Configuration)\ /Y</Command>
    </PostBuildEvent>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>Use</PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
    </Link>
  </ItemDefinitionGroup>
  <ItemGroup>
    <ClInclude Include="stdafx.h" />
    <ClInclude Include="targetver.h" />
  </ItemGroup>
  <ItemGroup>
    <ClCompile Include="ExampleClient.cpp" />
    <ClCompile Include="stdafx.cpp">
      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
    </ClCompile>
  </ItemGroup>
  <ItemGroup>
    <Manifest Include="ExampleClient.exe.manifest">
      <SubType>Designer</SubType>
    </Manifest>
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>

现在将调试器设置为目标 x86,将启动项目设置为 ExampleClient,然后运行应用程序。您可以单步执行它,您会注意到它运行时没有错误。按预期工作。

现在进入 TestClass.cs 并将类名更改为 TestClass2 之类的名称(不管怎样)。并且还进入 ExampleClient.cpp 并将对 TestClass 的引用更改为 TestClass2。重建解决方案。当您单步执行代码时,您将在尝试实例化 TestClass2 时遇到错误。要修复它,请转到 ExampleClient.exe.manifest 文件并将处理器架构更改为 msil。重建。然后将processorArchitecture改回x86。重建。现在该应用程序将再次运行。

您应该能够对 C# 库进行更改,并且只要您更改 C++ 应用程序以反射(reflect)它应该工作的更改。您不必来回切换处理器架构。一定有一些东西被缓存在某个地方,但我不知道在哪里。

最佳答案

在 Windows 10 上,操作系统似乎缓存了 list 加载。对于一个实验,我会尝试“触摸”你的 exe 和 exe list 文件的实验。如果您没有某种触摸,则此命令行将起作用:

powershell (ls $1).LastWriteTime = Get-Date

其中 $1 是文件名。我有一个 doskey 宏定义为
touch=powershell (ls $1).LastWriteTime = Get-Date

您可以尝试仅触摸 exe 或 list 。在 Windows 7 上,我以前可以注销或重新启动计算机以清除 list 缓存,但 Windows 10 似乎更难清除。所以我使用 touch 以便 Windows 忽略 list 缓存并从新文件加载。

(当我说“ list 缓存”时,这只是对我认为 Windows 在幕后所做的推断的描述)

关于c# - 当我更改 C# COM dll 的签名时,为什么我必须从 x86 到 msil 再回到 x86,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57713973/

相关文章:

c# - 为什么一个简单的 get-statement 这么慢?

c# - UDP 打洞问题

c++ - g++参数后的逗号

c++ - 无法使用启用的 BullseyeCoverage 和 Casablanca REST SDK 编译 Visual Studio 2013 C++ 项目

.net - Visual Studio 2008 单元测试和 nunit

c# - Excel ExportAsFixedFormat PDF

c# - 检查模型在 Controller 之外是否有效

c++ - 使用非x86架构上的非AVX指令移位xmm整数寄存器值

android - 使用 Xamarin 相机拍摄后如何提高图像质量?

c# - Visual Studio 2012 Express for Web 不运行单元测试