Do we have to keep the object alive while doing pinvoke?

C

cppdev

Hello,

After reading a few articles,
http://blogs.gotdotnet.com/cbrumme/PermaLink.aspx/e55664b4-6471-48b9-b360-f0fa27ab6cc0
http://blogs.gotdotnet.com/anathan/commentview.aspx/8ec0b7b2-6290-4500-a8c7-1b6c677214cb

i have the following question:

__gc class C
{
C(){ ptr = new Unmanaged(); }
~C(){ delete ptr; ptr = 0; }

void DoWork()
{

//Do we have to HandleRef ref(this, IntPtr(ptr));
ptr->UnmnagedCall();
//or call GC::KeepAlive(this)
}

Unmanaged __nogc* ptr;
};

Do we have to do
HandleRef ref(this, IntPtr(ptr)) or GC::KeepAlive?
No one seems to talk about this. Does MC++ take care of
this problem?

Thanx for any input
 
M

Mahesh Hariharan[MSFT]

Hello
The rules are very simple .

Consider a simple sync unmanaged call from a managed function.
What kind of data are you passing to the unmanaged function? Nothing ? You
have nothing to worrry about !
If you are only passing addresses of any managed data like a string
pointer, a garbage collection cycle can change them(remember the GC will
move the objected) and so using them from unmanaged functions is not safe.
That is why you will pin the variable. see code below

#using <mscorlib.dll>
using namespace System;
#include <vcclr.h>
#include <stdio.h>
int main()
{
String* s = "hello";
const __wchar_t __pin* pinned_ptr = PtrToStringChars(s);
//s will be alive till pinned_ptr is in scope. Sufficient for
Synchronous functions
wprintf(pinned_ptr); //unmanaged call

}

On the other hand , if you are making a async call, you want to keep a
Pinned GCHandle alive till the async call is complete. This is for
unmanaged functions manipulating the managed heap directly and so the need
to not move them .

THis is using IJW in MC++ . If you are using PINVOKE like in C# , the
pinvoke layer will take care of this for sync calls.
http://blogs.gotdotnet.com/cbrumme/default.aspx?date=2003-05-06T00:00:00
also has some data.

--------------------
 
Top