Calling conventions C# with Example



Calling conventions C# with Example

There're several conventions of calling functions, specifying who (caller or callee) pops arguments from the stack, 
how arguments are passed and in what order. C++ uses Cdecl calling convention by default, but C# expects 
StdCall, which is usually used by Windows API. You need to change one or the other: 
Change calling convention to StdCall in C++: 
extern "C"   declspec(dllexport) int   stdcall add(int a, int b) 
[DllImport("myDLL.dll")] 
Or, change calling convention to Cdecl in C#: 
extern "C" declspec(dllexport) int /*     cdecl*/  add(int a, int b) 
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)] 
 

If you want to use a function with Cdecl calling convention and a mangled name, your code will look like this: 
   declspec(dllexport) int add(int a, int b) 
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl, 
EntryPoint = "?add@@YAHHH@Z")] 
thiscall(  thiscall) is mainly used in functions that are members of a class. 
When a function uses thiscall(  thiscall) , a pointer to the class is passed down as the first parameter. 

0 Comment's

Comment Form

Submit Comment