Mixed-mode scenario with tracking handles to value types

This question was recently asked in the MSDN forums and answered by myself, and I am blogging it here so I have a page to link to if something similar gets asked again in that or some other forum. The OP had a C# caller that called a mixed-mode DLL’s method that took 3 arguments of type int%. This mixed-mode method then called a native function that took 3 arguments of type int* and modified all three of them. The OP was confused as to how to pass the int% values passed from C# to the native method. The central issue was that although int is a value type, int% is a tracking reference and needs to be pinned first. Once you do that, you just pass it to the native method. Example code snippet:

void nativefunc(int *p1, int *p2, int *p3)
{
  // . . .
}

void managedfunc([Out]int% mp1, [Out]int% mp2, [Out]int% mp3)
{
  pin_ptr<int> p1 = &mp1;
  pin_ptr<int> p2 = &mp2;
  pin_ptr<int> p3 = &mp3;

  nativefunc(p1, p2, p3);
}
Advertisements

One thought on “Mixed-mode scenario with tracking handles to value types

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s