How do I DllExport a C++ Class for use in a C# Application

后端 未结 5 523
独厮守ぢ
独厮守ぢ 2020-12-05 11:37

I have created a C++ Dll project which contains a class \"myCppClass\" and tried to Dll export it using the following code as described by: http://msdn.microsoft.com/en-us/l

5条回答
  •  心在旅途
    2020-12-05 12:15

    C# cannot directly import C++ classes (which are effectively name-mangled C interfaces).

    Your options are exposing the class via COM, creating a managed wrapper using C++/CLI or exposing a C-style interface. I would recommend the managed wrapper, since this is easiest and will give the best type safety.

    A C-style interface would look something like this (warning: untested code):

    extern "C" __declspec(dllexport)
    void* CExampleExport_New(int param1, double param2)
    {
        return new CExampleExport(param1, param2);
    }
    
    extern "C" __declspec(dllexport)
    int CExampleExport_ReadValue(void* this, int param)
    {
        return ((CExampleExport*)this)->ReadValue(param)
    }
    

    A C++/CLI-style wrapper would look like this (warning: untested code):

    ref class ExampleExport
    {
    private:
        CExampleExport* impl;
    public:
        ExampleExport(int param1, double param2)
        {
            impl = new CExampleExport(param1, param2);
        }
    
        int ReadValue(int param)
        {
            return impl->ReadValue(param);
        }
    
        ~ExampleExport()
        {
            delete impl;
        }
    };
    

提交回复
热议问题