开发者

Pass plain C# object to C++ and call a method on that object

I want to pass an object of a C# class to C++ and in the native c++ code want to call some method on that passed object.

    Public class MyClass{
    {
       bool IsThisValid()
       {
           IsValid(this);//Check the Native passing it this object
       }
       [DllImport("mylibraryinCpp.dll", EntryPoint="IsValid", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall) ]       
       static internal extern bool IsValid(object); 
    }//end of class

Now a want the C++ code to get this object and perform some operation on it. In the n开发者_JAVA技巧ative C++ code I have the signature as

    //Native C++ code mylibraryinCpp.dll
    extern "C" __declspec(dllexport) BOOL __stdcall IsValid (VARIANT theObject)
    {
 ((mscorlib::_object*)(thObject.pdispVal))->get_ToString(bstrStringVal);//AccessViolationException occurs here.
    }

The above code is working most of the times but sometimes it is giving the AccessViolationException , other memory might be corrupt message. I am new to this so not sure is this the right way to pass object from C# to C++? Thanks for any suggestions


The object may be moved by the garbage collector. Normally, you would just pass a function pointer to native code- it can be generated from a delegate in .NET by the JIT- which definitely works. This is known as reverse P/Invoke.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜