如何从C#托管代码调用本机C ++类的方法?

时间:2017-11-20 12:03:56

标签: c# c++ native unmanaged managed

我有两个库LibCPP.dll(本机C ++)和LibCS.dll(托管C#)。 LibCS.dll使用Robert Giesecke DllExport导出一些函数。 LibCPP.dll加载LibCS.dll并使用这些函数。

我需要进行以下操作:在LibCPP.dll端创建本机C ++类对象,并将指向该对象的指针作为某些函数的参数发送到LibCS.dll。如何通过收到的指针在LibCS.dll端调用C ++类方法?

LibCS.dll端的代码示例:

public static class ExportClass
    {
        [DllExport(ExportName = "SimpleFunction", CallingConvention = CallingConvention.StdCall)]
        public static int SimpleFunction(int a, int b)
        {
            return a + b;
        }

        [DllExport(ExportName = "CPPObjectMethodCall", CallingConvention = CallingConvention.StdCall)]
        public static bool CPPObjectMethodCall(IntPtr cppObject)
        {
            // How to make call of c++ object method here?
        }

    }

LibCPP.dll端的代码示例:

class CPPClass
{
    public :
        CPPClass() {}

        ~CPPClass() {}

        void CPPClassMethodCall(std :: string text)
        {
            MessageBoxA(NULL, text.c_str(), "Message", 0);
        }
};


void TestFunction()
{
    HMODULE hDLL = LoadLibraryA("LibCS.dll");

    typedef int (*SIMPLEFUNCTION)(int a, int b);
    typedef bool (*CPPOBJECTMETHODCALL)(void * cppObject);

    SIMPLEFUNCTION SimpleFunction = (SIMPLEFUNCTION)GetProcAddress(hDLL, "SimpleFunction");
    CPPOBJECTMETHODCALL CPPObjectMethodCall = (CPPOBJECTMETHODCALL)GetProcAddress(hDLL, "CPPObjectMethodCall");

    int x = SimpleFunction(1, 2);

    CPPClass * cppObject = new CPPClass();

    // Pass pointer to C++ object 
    CPPObjectMethodCall(cppObject);

    delete cppObject;

    FreeLibrary(hDLL);
}

0 个答案:

没有答案