无法从 C++/Cli 调用静态 C# 方法

Unable to call static C# method from C++/Cli

我正在尝试从 C++/Cli 调用 C# 方法。此方法在 ClassLibrary1.dll 中定义。我不断收到以下错误:

An unhandled exception of type 'System.MissingMethodException' occurred in Unknown Module.

Additional information: Method not found: 'Int32 ClassLibrary1.Class1.getNum()'.

这是我的 C++/Cli 代码:

//CppClr.cpp

#include "CppClr.h"
#using "ClassLibrary1.dll"
using namespace ClassLibrary1;
int main()
{
    System::Console::WriteLine("Start");
    int num = Class1::getNum();
    System::Console::WriteLine(num);
    System::Console::ReadLine();
}

我的 C# 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ClassLibrary1
{
    public class Class1
    {
        public static int getNum()
        {
            return 5;
        }
    }
}

MissingMethodException 总是由在运行时加载错误的程序集引起的。通常是旧的。

在同时具有 C# 和 C++/CLI 项目的解决方案中容易犯的错误。它们有不同的标准,C# 程序集构建到项目的 bin\Debug 目录,但 C++/CLI 项目构建到解决方案的 Debug 目录。您可能已经发现了这一点,通过自己复制 C# 程序集修复了它,但在更改 C# 代码后忘记再次执行此操作。

只需确保两个项目都构建到相同的 目录。 Right-click C# 项目 > 属性 > 构建选项卡 > 输出路径设置。将其从 "bin\Debug" 更改为“..\Debug”。重复发布配置。重建并验证您在解决方案的调试目录中看到了 EXE 和 DLL 的最新副本。