[Mono-list] using 'unsafe struct *' instead of IntPtr with PInvoke..

jeske davidj at gmail.com
Wed Dec 22 18:35:06 EST 2010


This is a fairly subtle question about PInvoke and GC interaction. It's
related to .NET in general, not just mono, but I figure folks implementing a
.NET runtime may actually know the answer. 

Platform Invoke documentation advocates using System.IntPtr as an opaque
type. However, this is a single opaque type, which eliminates typechecking
that could be done to distinguish different opaque types. 

In writing PInvoke modules with many native pointer types, I want the
compiler to type-check different native pointer types, so I've begun to use
a different pattern with unsafe structs pointers. I'm writing to find out if
anyone believes this is invalid for any reason. Instead of storing an IntPtr
for later use, I declare an opaque struct type and use it to hold a pointer.
For example: 

class Foo { 
  unsafe struct FOO {}; // opaque type 
  unsafe FOO* my_foo; // instead of IntPtr 

  [DllImport("mylibary")] 
  extern static unsafe FOO* get_foo(); 

  [DllImport("mylibrary")] 
  extern static unsafe do_something_foo(FOO *foo); 

  public unsafe Foo() { 
    this.my_foo = get_foo(); 
  } 
  public unsafe doSomethingFoo() { 
    do_something_foo(this.my_foo); 
  } 
} 

Is there anything wrong with this pattern? For example, is this "unsafe FOO
*my_foo" something that I can assume the GC system will completely leave
alone, or will the GC try to trace it in some way? 

At a deeper level, I wonder why Platform Invoke doesn't advocate using
something like this more often, because it's alot safer than storing and
passing everything around as IntPtr. 

Thoughts? 

-- 
View this message in context: http://mono.1490590.n4.nabble.com/using-unsafe-struct-instead-of-IntPtr-with-PInvoke-tp3161427p3161427.html
Sent from the Mono - General mailing list archive at Nabble.com.


More information about the Mono-list mailing list