Mercurial > hg > ucis.core
comparison Util/InteropUtil.cs @ 76:b05350c24596
Added InteropUtil for safe pinned array and string access
author | Ivo Smits <Ivo@UCIS.nl> |
---|---|
date | Mon, 03 Feb 2014 22:53:58 +0100 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
75:50d4aed66c67 | 76:b05350c24596 |
---|---|
1 using System; | |
2 using System.Collections.Generic; | |
3 using System.Text; | |
4 using System.IO; | |
5 using System.Runtime.InteropServices; | |
6 | |
7 namespace UCIS.Util { | |
8 public class PinnedObject : SafeHandle { | |
9 GCHandle gch; | |
10 public PinnedObject(Object obj) | |
11 : base(IntPtr.Zero, true) { | |
12 gch = GCHandle.Alloc(obj, GCHandleType.Pinned); | |
13 SetHandle(gch.AddrOfPinnedObject()); | |
14 } | |
15 public override bool IsInvalid { get { return handle == IntPtr.Zero; } } | |
16 protected override bool ReleaseHandle() { | |
17 if (gch.IsAllocated) { | |
18 gch.Free(); | |
19 return true; | |
20 } else { | |
21 return false; | |
22 } | |
23 } | |
24 public static implicit operator IntPtr(PinnedObject p) { return p.DangerousGetHandle(); } | |
25 public static implicit operator PinnedObject(Array o) { return new PinnedObject(o); } | |
26 } | |
27 public class PinnedString : SafeHandle { | |
28 public PinnedString(String str, Boolean unicode) | |
29 : base(IntPtr.Zero, true) { | |
30 SetHandle(unicode ? Marshal.StringToHGlobalUni(str) : Marshal.StringToHGlobalAnsi(str)); | |
31 } | |
32 public override bool IsInvalid { get { return handle == IntPtr.Zero; } } | |
33 protected override bool ReleaseHandle() { | |
34 Marshal.FreeHGlobal(handle); | |
35 return true; | |
36 } | |
37 public static implicit operator IntPtr(PinnedString p) { return p.DangerousGetHandle(); } | |
38 } | |
39 public class PinnedStringAnsi : PinnedString { | |
40 public PinnedStringAnsi(String str) : base(str, false) { } | |
41 public static implicit operator PinnedStringAnsi(String s) { return new PinnedStringAnsi(s); } | |
42 } | |
43 public class PinnedStringUni : PinnedString { | |
44 public PinnedStringUni(String str) : base(str, true) { } | |
45 public static implicit operator PinnedStringUni(String s) { return new PinnedStringUni(s); } | |
46 } | |
47 } |