How to set up a C++ function so that it can be used by p/invoke?

前端 未结 6 677
旧巷少年郎
旧巷少年郎 2020-12-30 13:01

Hopefully this is a brainlessly easy question, but it shows my lack of expertise with C++. I\'m a C# programmer, and I\'ve done extensive work with P/Invoke in the past wit

6条回答
  •  情深已故
    2020-12-30 13:24

    The C++ compiler modifies the names of your functions to incorporate information about the parameters and return types. This is called name mangling. On the other hand, the C compiler doesn't mangle your function names.

    You can tell the C++ compiler to work as a C compiler using extern "C":

    extern "C" __declspec(dllexport) bool TestFunc { return true; }
    

    To call functions from C# using P/Invoke, your names must not be mangled. Therefore, you can actually export C functions to C#. If you want the functionality to be implemented in C++, you can write a C function that just calls the C++ function implementing the functionality.

提交回复
热议问题