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

前端 未结 6 682
旧巷少年郎
旧巷少年郎 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:23

    Extending Reed's correct answer.

    Another issue you can run into when exposing a C++ function via PInvoke is using invalid types. PInvoke can really only support marshalling of primitive types and plain old data struct / class types.

    For example, suppose TestFunc had the following signature

    void TestFunc(std::string input);
    

    Even adding extern "C" and __declspec(dllexport) would not be enough to expose the C++ function. Instead you would need to create a helper function which exposed only PInvoke compatible types and then called into the main function. For example

    void TestFunc(const std::string& input) { ... }
    
    extern "C" _declspec(dllexport)  void TestFuncWrapper(char* pInput) {
      std::string input(pInput);
      TestFunc(input);
    }
    

提交回复
热议问题