C# – declspec and stdcall vs declspec only

cdllimportstdcall

I'm a new person to C++ dll import topic and may be my question is very easy but I can not find it on google.

I have a very simple C++ win32 dll:

#include <iostream>

using namespace std;

extern "C"
{
    __declspec(dllexport) void __stdcall DisplayHellowFromDLL()
    {
        cout<<"Hi"<<endl;
    }
}

When I call this method from C# I do not have any problem, here is C# code

namespace UnmanagedTester
{
    class Program
    {
        [DllImport(@"C:\CGlobalDll")]
        public static extern void DisplayHellowFromDLL();

        static void Main(string[] args)
            {
                Console.WriteLine("This is C# program");
                DisplayHellowFromDLL();
            }
        }
    }

As I expected the output is: "This is C# program" "Hi".

Now if I change the declaration of C function as:

__declspec(dllexport) void DisplayHellowFromDLL()

without __stdcall, I do not have any problem as well, and the question is:

When do I really need __declspec(dllexport) TYPE __stdcall and when I can use only __declspec(dllexport) TYPE ?

Thanks a lot.

Best Answer

You can think of it like this:

  1. __declspec(dllexport) declares your function as a public function that your DLL exports;

  2. __stdcall is a rather low-level detail that refers to the "calling convention" adopted by that function; specifically, __stdcall means that the callee cleans the stack;

  3. alternative to __stdcall is __cdecl, which means: the caller cleans the stack.

__cdecl is the "natural" C calling convention; it supports the definition of vararg functions (like printf).

__stdcall is the default calling convention for DLL functions, so you don't need specify it if you are only going to call those functions through their DLL API.

This should explain what you are observing.