[Mono-list] IntPtr safety (was: need some help with PInvoke..)
Hervé Poussineau
poussine@freesurf.fr
Fri, 11 Jul 2003 09:54:39 +0200
>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
public struct HWndPtr : ISerializable
{
private IntPtr _Pointer;
public static readonly HWndPtr Zero = new
HWndPtr(IntPtr.Zero.ToInt64());
public static int Size { get { return IntPtr.Size; } }
public HWndPtr(int hWnd) { _Pointer = new IntPtr(hWnd); }
public HWndPtr(long hWnd) { _Pointer = new IntPtr(hWnd); }
unsafe public HWndPtr(void* hWnd) { _Pointer = new IntPtr(hWnd); }
public int ToInt32() { return _Pointer.ToInt32(); }
public long ToInt64() { return _Pointer.ToInt64(); }
public IntPtr ToIntPtr() { return _Pointer; }
[CLSCompliant(false)]
unsafe public void* ToPointer() { return _Pointer.ToPointer(); }
public static bool operator == (HWndPtr value1, HWndPtr value2)
{ return value1._Pointer == value2._Pointer; }
public static bool operator != (HWndPtr value1, HWndPtr value2)
{ return value1._Pointer != value2._Pointer; }
public static explicit operator HWndPtr(int value)
{ return new HWndPtr(value); }
public static explicit operator HWndPtr(long value)
{ return new HWndPtr(value); }
public static explicit operator int(HWndPtr value)
{ return (int)value._Pointer; }
public static explicit operator long(HWndPtr value)
{ return (long)value._Pointer; }
[CLSCompliant(false)]
unsafe public static explicit operator void*(HWndPtr value)
{ return (void*)value._Pointer; }
[CLSCompliant(false)]
unsafe public static explicit operator HWndPtr(void* value)
{ return new HWndPtr(value); }
public void GetObjectData(SerializationInfo info, StreamingContext
context)
{ throw new NotImplementedException(); }
}
Hervé
PS: I hope you will understand my English...