1

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 native 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

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Doesn't the object get marshaled?
@svick: No. .NET generates a new function which has an object reference in it statically, and then passes that function pointer. Effectively.
Thanks @DeadMG , doess this reverse P/Invoke applicable even for non static function?Will I be able to say invoke "xyz" method of this object instance?
Using P/Invoke I was able to achieve what was needed. Thanks for the suggestion. However why the object getting GCd when in one odd case consistently where as it works fine all other times still bothers me. Is there any way I can avoid that , so that i dont have to change my implemenation? or is there a way to be sure that the Object is indeed getting GCed is the reason for the problem?
@Prakash: The GC is non-deterministic- it collects whenever it likes. Reverse P/Invoke is good for member functions, yes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.