Dumpbin shows a strange method name (creating an export function in MS Visual C ++)

I created a new Win32 project in my VS and selected Dynamic Library (* .dll) for this purpose.

I defined some export function in the main file:

__declspec(dllexport) int TestCall(void) { int value = 4 / 2; std::cout << typeid(value).name() << std::endl; return value; } __declspec(dllexport) void SwapMe(int *first, int *second) { int tmp = *first; *first = *second; *second = tmp; } 

When I looked at dumpin / exports, I have:

 ordinal hint RVA name 1 0 00001010 ?SwapMe@ @ YAXPEAH0@Z 2 1 00001270 ?TestCall@ @YAHXZ 

I call the C # version as follows:

 [DllImport(@"lib1.dll", EntryPoint = " ?TestCall@ @YAHXZ", CallingConvention = CallingConvention.Cdecl)] static extern int TestCall(); 

This is not the right way to use exported methods. Where have I mistakenly generated such names for exporting methods in a C ++ dll project?

+1
source share
2 answers

This is normal, the C ++ compiler applies name decoration to functions. The C ++ language supports function overloading, as C # does. So you can write the function Foo(int) and Foo(double) . Obviously, they cannot be exported as a function named "Foo", the client code will not know which one to call. Thus, additional characters encode the name so that it is unique to the overload.

You can disable this by declaring the extern "C" function extern "C" , the C language does not support overloading, therefore it does not require the same design.

But actually it’s better if you don’t. Because it is also a great way to catch bugs. Like changing a function declaration in your C ++ code, but forgetting to change the pinvoke declaration in C # code. Now you can easily diagnose the "Entrypoint not found" exception instead of the non-descriptive and very difficult AccessViolationException to diagnose. Which does not have to be raised in C ++ code, a stack imbalance can also lead to a failure of your C # code. However, finding the decorated name is a little painful, improve this by asking the linker to create a map file (/ MAP).

+5
source

use extern "C" to indicate a link to avoid name manipulation:

 extern "C" __declspec(dllexport) int TestCall(void); extern "C" __declspec(dllexport) void SwapMe(int *first, int *second); 
+2
source

Source: https://habr.com/ru/post/1497192/


All Articles