]> git.meshlink.io Git - catta/blob - avahi-sharp/Utility.cs
add initial mono bindings
[catta] / avahi-sharp / Utility.cs
1 using System;
2 using System.Net;
3 using System.Text;
4 using System.Runtime.InteropServices;
5 using Mono.Unix;
6
7
8 namespace Avahi
9 {
10     internal class Utility
11     {
12         [DllImport ("libc")]
13         private static extern int strlen (IntPtr ptr);
14
15         [DllImport ("avahi-common")]
16         private static extern IntPtr avahi_address_snprint (IntPtr buf, int size, IntPtr address);
17
18         public static string PtrToString (IntPtr ptr)
19         {
20             if (ptr == IntPtr.Zero)
21                 return null;
22             
23             int len = strlen (ptr);
24             byte[] bytes = new byte[len];
25             Marshal.Copy (ptr, bytes, 0, len);
26             return Encoding.UTF8.GetString (bytes);
27         }
28
29         public static string PtrToStringFree (IntPtr ptr)
30         {
31             if (ptr == IntPtr.Zero)
32                 return null;
33             
34             string ret = PtrToString (ptr);
35             Free (ptr);
36             return ret;
37         }
38
39         public static IntPtr StringToPtr (string str)
40         {
41             if (str == null)
42                 return IntPtr.Zero;
43
44             byte[] bytes = Encoding.UTF8.GetBytes (str);
45             IntPtr buf = Stdlib.malloc ((uint) bytes.Length + 1);
46             Marshal.Copy (bytes, 0, buf, bytes.Length);
47             Marshal.WriteByte (buf, bytes.Length, 0);
48             return buf;
49         }
50
51         public static void Free (IntPtr ptr)
52         {
53             Stdlib.free (ptr);
54         }
55
56         public static IPAddress PtrToAddress (IntPtr ptr)
57         {
58             IPAddress address = null;
59             
60             if (ptr != IntPtr.Zero) {
61                 IntPtr buf = Stdlib.malloc (256);
62                 IntPtr addrPtr = avahi_address_snprint (buf, 256, ptr);
63                 address = IPAddress.Parse (Utility.PtrToString (addrPtr));
64                 Utility.Free (addrPtr);
65             }
66
67             return address;
68         }
69     }
70 }