C++ compilers encode additional information in the names of exported functions, such as argument types, to make overloads with different arguments possible. This process is called name mangling. This causes problems with importing functions in C# (and interop with other languages in general), as the name of int add(int a, int b)
function is no longer add
, it can be ?add@@YAHHH@Z
, _add@8
or anything else, depending on the compiler and the calling convention.
There're several ways of solving the problem of name mangling:
Exporting functions using extern "C"
to switch to C external linkage which uses C name mangling:
extern "C" __declspec(dllexport) int __stdcall add(int a, int b)
[DllImport("myDLL.dll")]
Function name will still be mangled (_add@8
), but StdCall
+extern "C"
name mangling is recognized by C# compiler.
Specifying exported function names in myDLL.def
module definition file:
EXPORTS
add
int __stdcall add(int a, int b)
[DllImport("myDLL.dll")]
The function name will be pure add
in this case.
Importing mangled name. You'll need some DLL viewer to see the mangled name, then you can specify it explicitly:
__declspec(dllexport) int __stdcall add(int a, int b)
[DllImport("myDLL.dll", EntryPoint = "?add@@YGHHH@Z")]