tags:

views:

67

answers:

1

I'm trying to learn the basics of tying up unmanaged C++ and .NET. So, I've got the DLL compiled and callable from C#. Great. Now I run into this weird problem:

Here's my C++ file, Main.cpp:

#include <stdio.h>

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

and C# file, 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();


       }
    }
}

Simple enough. When build, I get ConsoleApp.dll from the C++ side, and FancyApp.exe from C#.

When run, it outputs

Hello form the World of 2008!

Hello from the World of 1986!

Press any key to exit

as it should, except in Release mode from VS2008 (Press F5), I get

Hello form the World of 2008!

Press any key to exit

Now, if I go to Explorer and run the release build of FancyApp.exe without VS, it runs fine.

Ideas?

I've uploaded my solutions folder here (180kb).

+3  A: 

Well I see the same behavior here, and I can't fully explain it. However I think that trying to run in debug mode (F5) against a Release build, you should expect undefined behavior. If I use ctrl-F5 it runs properly.

Since that's working, we can deduce that the binary is correctly built, so there's no compiler issue, but instead you're seeing some strange artifact of the debugger.

This can be proven by going into the properties of FancyApp and on the Debug tab unchecking 'Enable the Visual Studio hosting process'. If you do that it works as you're expecting. Why, exactly, I can't say. The lesson here is don't try to debug a release build.

ctacke