declspec and stdcall vs declspec only
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 开发者_Python百科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.
You can think of it like this:
__declspec(dllexport)
declares your function as a public function that your DLL exports;__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;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.
It works by accident because the function doesn't take any arguments. As soon as you do this on a function that does take arguments you'll start running out of luck. The call will leave the stack imbalanced, very unhealthy. You'd get the pInvokeStackImbalance MDA warning when you debug. An imbalanced stack can otherwise go unnoticed for a while, it tends to crash your program in the Release build.
You need to specify the calling convention if you compile the calling code with some other convention. Otherwise the default will work.
Ilya, you can also set the default calling convention in Project Properties -> Configuration Properties -> C/C++ -> Advanced -> Calling Convention. If the default calling convention in your project is already set to __stdcall (/Gz), then adding __std
精彩评论