gpt4 book ai didi

c# - 奇怪的 DLL + InterropServices 问题

转载 作者:行者123 更新时间:2023-11-30 03:12:45 25 4
gpt4 key购买 nike

我正在努力学习结合非托管 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com