C# P\Invoke DLL no entry point into C++?

前端 未结 3 487
南笙
南笙 2021-01-24 06:33

I have a C++ Dll \"TheFoo.dll\" with a method \"Foo()\"

I have access to other C++ code that uses this method by simply calling:

Foo();

3条回答
  •  天命终不由人
    2021-01-24 07:25

    The C++ language supports overloading, much like C# does. You could export an function void Foo(int) and a function void Foo(double). Clearly those two functions could not both be exported as "Foo", the client of the DLL wouldn't know which one to pick. So it is not.

    The C++ compiler solves that problem by decorating the name of the function. Adding extra characters that makes a Foo(int) different from a Foo(double). You can see those decorated names by running Dumpbin.exe /exports foo.dll from the Visual Studio Command Prompt, that lists the name of the exported functions. Assuming your declaration was relevant, you'd see ?Foo@@YAXXZ.

    So the corresponding declaration in your C# program should be:

        [DllImport("foo.dll", EntryPoint = "?Foo@@YAXXZ", 
                   ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
        private static extern void Foo();
    

    There are ways to change the C++ function declaration to make the C# declaration easier. Which is actually not a good idea, these decorated names actually help catch mistakes.

提交回复
热议问题