c# - 奇怪的 DLL + InterropServices 问题

标签 c# c++ dll interop

我正在努力学习结合非托管 C++ 和 .NET 的基础知识。所以,我已经从 C# 编译并调用了 DLL。伟大的。现在我遇到了这个奇怪的问题:

这是我的 C++ 文件,Main.cpp:

#include <stdio.h>

extern "C" __declspec(dllexport) void DisplayHelloFromDLL()
{
    printf ("Hello from the World of 1986!\n");
}

和C#文件,Program.cs:

using System; using System.Runtime.InteropServices;

namespace FancyApp {
    class Program
    {
        [DllImport("ConsoleApp.dll")]
        public static extern void DisplayHelloFromDLL();

        static void Main()
        {
            Console.WriteLine("Hello form the World of 2008!");
            DisplayHelloFromDLL();

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();


       }
    }
}

很简单。构建时,我从 C++ 端获取 ConsoleApp.dll,从 C# 获取 FancyApp.exe

运行时输出

Hello form the World of 2008!

Hello from the World of 1986!

Press any key to exit

因为它应该,除了在 VS2008 的 Release模式下(按 F5),我得到

Hello form the World of 2008!

Press any key to exit

现在,如果我转到资源管理器并在没有 VS 的情况下运行 FancyApp.exe 的发布版本,它运行良好。

想法?

我已经上传了我的解决方案文件夹 here (180kb)。

最佳答案

好吧,我在这里看到了相同的行为,但我无法完全解释它。但是我认为尝试在 Debug模式 (F5) 下针对发布版本运行时,您应该预料到未定义的行为。如果我使用 ctrl-F5,它会正常运行。

由于它有效,我们可以推断二进制文件已正确构建,因此不存在编译器问题,但您会看到一些奇怪的调试器工件。

这可以通过进入 FancyApp 的属性并在“调试”选项卡上取消选中“启用 Visual Studio 托管进程”来证明。如果你这样做,它就会像你期望的那样工作。为什么,确切地说,我不能说。这里的教训是不要尝试调试发布版本。

关于c# - 奇怪的 DLL + InterropServices 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/391693/

相关文章:

c# - x :Name in XAML WPF - Visual Studio Community 2017 BUG

c++ - 在具有通用引用参数的函数模板中使用类模板

c++ - 处理 com 版本中可能不存在的功能

c# - C# 什么时候释放 C++ DLL?

c# - 如何使用 Reactive UI 在单击按钮与按下按钮(按住)后触发不同的操作

c# - 从wmi获取每个进程的Cpu使用率

c# - 在 C# 中获取唯一标识符的最佳方法

android - ndk-gdb 无法找到 gdb.setup

c++ - 比较 uint64_t 和 float 的数值等价性

c# - 在非托管 c++ dll 中使用托管 c# dll