How do I pass a ref in managed code to a unmanaged code function?

  • Thread starter Thread starter mmobile
  • Start date Start date
M

mmobile

How to I pass(marshal) a reference in managed code to a unmanaged code
function?

For example:

In my unmanaged code I have a function like:
int InsertItem(HWND hWnd, long tag)

In my managed code I declare
class TestApp
{
...
[DllImport("Test.dll")]
public extern static int InsertItem(InPtr hWnd, long tag)
...

TestApp()
{
TestApp.InsertItem(this.hWnd, this.myObject); // How do I pass the
reference(address) of this.myObject????????????
}
}

All I want to do is store the reference(address) to the object in the
managed code. I won't be accessing the object from the managed code.
 
Hello, mmobile!

m> For example:

m> In my unmanaged code I have a function like:
m> int InsertItem(HWND hWnd, long tag)

m> In my managed code I declare
m> class TestApp
m> {
m> ...
m> [DllImport("Test.dll")]
m> public extern static int InsertItem(InPtr hWnd, long tag)
m> ...

m> TestApp()
m> {
m> TestApp.InsertItem(this.hWnd, this.myObject); // How do I pass
m> the reference(address) of this.myObject????????????
m> }
m> }

Why do you need this? You will not be able to do anything with managed object from unmanaged environment using its address. Also object address in memory can change due to GC heap defragmentation.

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
 
This should work(I Think):

GCHandle gc = new GCHandle();
gc.Target = this.myObject;
IntPtr address = gc.AddrOfPinnedObject();//prevents the GC from moving
the object around
TestApp.InsertItem(this.hWnd, address);
 
Back
Top