[Mono-list] IntPtr safety (was: need some help with PInvoke..)

David Jeske jeske@chat.net
Fri, 11 Jul 2003 01:39:18 -0700


On Fri, Jul 11, 2003 at 09:54:39AM +0200, Hervé Poussineau wrote:
> >I guess this is my confusion. HWND* is _safer_ than IntPtr, because it
> >is a pointer to a specific type. It's the operations on HWND* that are
> >unsafe. It seems like it would be better if VB (and other languages
> >without unsafe) had the ability to express HWND*, and simply not
> >operate on it.
> >
> >Certainly this:
> >    .field  public   valuetype HDF* p
> >
> >Is better than this:
> >    .field  public   native int p
> 
> Why don't you write a struct that contains only a HWND* ? So, you can simply
> express your HWND* in safe code. Moreover, you can mark certain methods as
> "internal" for more security

I think you may be confused because of how I mixed up a few
comments. Let me clarify:

1) I'm plenty happy making my own struct which has no elements and
   using it as a strongly typed pointer. My code looks like this, and
   I'm happy with it:

    unsafe struct NEOERR { 
      // this one has members, non-opaque
    };
    unsafe struct HDF { }; // opaque
    unsafe struct CSP { }; // opaque
    // more opaque types

    [Dllimport("libneo.dll")] extern static NEOERR *hdf_init(HDF **);


2) I find it really dangerous that S.W.F exposes HWND* structures as
   IntPtr. Any method in an assembly that is accessable that takes an
   IntPtr as a paramater or which lets you access an IntPtr as a
   public field can be used to crash the runtime by sticking the
   wrong type of IntPtr there. This seems "really bad". 

   It seems like this might have been done to support VB's common use
   of "ByRef HWND as Long" since it dosn't have pointer types. Ohh
   well.

In response to your comment. I already have a managed type which wraps
the HDF*. The thing is, I have a few different components of my
wrapper which need access to the raw HDF*. Wrapping a void*
(i.e. IntPtr) in another level of managed type seems needless and
performance-sapping when the unsafe HDF* does exactly what I want, not
to mention un-type-safe.

I'm plenty happy with how this works now.. (although I have run into
some other interesting issues.. more later)

-- 
David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske@chat.net