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

前端 未结 3 448
南笙
南笙 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:15

    You should provide more information on your C++. Try using extern "C" __declspec(dllexport) instead. C++ exports with strange names so using extern "C" avoids that.

    0 讨论(0)
  • 2021-01-24 07:21

    If you didn't declare it extern "C" in your dll, its name has likely been "mangled". You can use something like Dependency Walker to see what symbols your dll exports.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题