ustring.cs 2.55 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
 * ustring.cs - Managed LibVLC string
 *
 * $Id$
 */

/**********************************************************************
 *  Copyright (C) 2007 Rémi Denis-Courmont.                           *
 *  This program is free software; you can redistribute and/or modify *
 *  it under the terms of the GNU General Public License as published *
 *  by the Free Software Foundation; version 2 of the license, or (at *
 *  your option) any later version.                                   *
 *                                                                    *
 *  This program is distributed in the hope that it will be useful,   *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of    *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.              *
 *  See the GNU General Public License for more details.              *
 *                                                                    *
 *  You should have received a copy of the GNU General Public License *
 *  along with this program; if not, you can get it from:             *
 *  http://www.gnu.org/copyleft/gpl.html                              *
 **********************************************************************/

using System;
using System.Runtime.InteropServices;

namespace VideoLAN.LibVLC
{
    /**
     * Managed class for UTF-8 nul-terminated character arrays
     */
    [StructLayout (LayoutKind.Sequential)]
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
33
    public struct U8String
34
35
36
37
38
    {
        public byte[] mb_str;

        public U8String (string value)
        {
39
            mb_str = null;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
40
41
42
            if (value == null)
                return;

43
44
45
46
47
48
49
50
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes (value);
            mb_str = new byte[bytes.Length + 1];
            Array.Copy (bytes, mb_str, bytes.Length);
            mb_str[bytes.Length] = 0;
        }

        public U8String (IntPtr ptr)
        {
51
            mb_str = null;
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
            if (ptr == IntPtr.Zero)
                return;

            int i = 0;
            while (Marshal.ReadByte (ptr, i) != 0)
                i++;
            i++;

            mb_str = new byte[i];
            Marshal.Copy (ptr, mb_str, 0, i);
        }

        public override string ToString ()
        {
            if (mb_str == null)
                return null;

            byte[] bytes = new byte[mb_str.Length - 1];
            Array.Copy (mb_str, bytes, bytes.Length);

            return System.Text.Encoding.UTF8.GetString (bytes);
        }

        public static string FromNative (IntPtr ptr)
        {
            return new U8String (ptr).ToString ();
        }
    };
};