]> git.sesse.net Git - vlc/blob - bindings/cil/src/ustring.cs
Clone video filter : fix potential memleak.
[vlc] / bindings / cil / src / ustring.cs
1 /*
2  * ustring.cs - Managed LibVLC string
3  *
4  * $Id$
5  */
6
7 /**********************************************************************
8  *  Copyright (C) 2007 RĂ©mi Denis-Courmont.                           *
9  *  This program is free software; you can redistribute and/or modify *
10  *  it under the terms of the GNU General Public License as published *
11  *  by the Free Software Foundation; version 2 of the license, or (at *
12  *  your option) any later version.                                   *
13  *                                                                    *
14  *  This program is distributed in the hope that it will be useful,   *
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of    *
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.              *
17  *  See the GNU General Public License for more details.              *
18  *                                                                    *
19  *  You should have received a copy of the GNU General Public License *
20  *  along with this program; if not, you can get it from:             *
21  *  http://www.gnu.org/copyleft/gpl.html                              *
22  **********************************************************************/
23
24 using System;
25 using System.Runtime.InteropServices;
26
27 namespace VideoLAN.LibVLC
28 {
29     /**
30      * Managed class for UTF-8 nul-terminated character arrays
31      */
32     [StructLayout (LayoutKind.Sequential)]
33     public struct U8String
34     {
35         public byte[] mb_str;
36
37         public U8String (string value)
38         {
39             mb_str = null;
40             if (value == null)
41                 return;
42
43             byte[] bytes = System.Text.Encoding.UTF8.GetBytes (value);
44             mb_str = new byte[bytes.Length + 1];
45             Array.Copy (bytes, mb_str, bytes.Length);
46             mb_str[bytes.Length] = 0;
47         }
48
49         public U8String (IntPtr ptr)
50         {
51             mb_str = null;
52             if (ptr == IntPtr.Zero)
53                 return;
54
55             int i = 0;
56             while (Marshal.ReadByte (ptr, i) != 0)
57                 i++;
58             i++;
59
60             mb_str = new byte[i];
61             Marshal.Copy (ptr, mb_str, 0, i);
62         }
63
64         public override string ToString ()
65         {
66             if (mb_str == null)
67                 return null;
68
69             byte[] bytes = new byte[mb_str.Length - 1];
70             Array.Copy (mb_str, bytes, bytes.Length);
71
72             return System.Text.Encoding.UTF8.GetString (bytes);
73         }
74
75         public static string FromNative (IntPtr ptr)
76         {
77             return new U8String (ptr).ToString ();
78         }
79     };
80 };