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.
__declspec(dllimport) is a storage-class specifier that tells the compiler that a function or object or data type is defined in an external DLL. The function or object or data type is exported from a DLL with a corresponding __declspec(dllexport) . Follow this answer to receive notifications.
The __declspec(dllexport) attribute exports the definition of a symbol through the dynamic symbol table when building DLL libraries.
You can export an entire C++ class by placing the __declspec(dllexport) before the class name, or you can export a single method by placing __declspec(dllexport) before the method name. Make class methods static and public. The C/C++ DLL Adapter does not allow you to call public non-static methods.
The dllexport and dllimport storage-class attributes are Microsoft-specific extensions to the C and C++ languages. You can use them to export and import functions, data, and objects to or from a DLL.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With