1 // GLib.Argv.cs : Argv marshaling class
2 //
3 // Author: Mike Kestner  <mkestner@novell.com>
4 //
5 // Copyright (c) 2004 Novell, Inc.
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of version 2 of the Lesser GNU General
9 // Public License as published by the Free Software Foundation.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this program; if not, write to the
18 // Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 // Boston, MA 02111-1307, USA.
20 
21 
22 namespace GLib {
23 
24 	using System;
25 	using System.Runtime.InteropServices;
26 
27 	public class Argv {
28 
29 		IntPtr[] arg_ptrs;
30 		IntPtr handle;
31 		bool add_progname = false;
32 
~Argv()33 		~Argv ()
34 		{
35 			Marshaller.Free (arg_ptrs);
36 			Marshaller.Free (handle);
37 		}
38 
Argv(string[] args)39 		public Argv (string[] args) : this (args, false) {}
40 
Argv(string[] args, bool add_program_name)41 		public Argv (string[] args, bool add_program_name)
42 		{
43 			add_progname = add_program_name;
44 			if (add_progname) {
45 				string[] full = new string [args.Length + 1];
46 				full [0] = System.Environment.GetCommandLineArgs ()[0];
47 				args.CopyTo (full, 1);
48 				args = full;
49 			}
50 
51 			arg_ptrs = new IntPtr [args.Length];
52 
53 			for (int i = 0; i < args.Length; i++)
54 				arg_ptrs [i] = Marshaller.StringToPtrGStrdup (args[i]);
55 
56 			handle = Marshaller.Malloc ((ulong)(IntPtr.Size * args.Length));
57 
58 			for (int i = 0; i < args.Length; i++)
59 				Marshal.WriteIntPtr (handle, i * IntPtr.Size, arg_ptrs [i]);
60 		}
61 
62 		public IntPtr Handle {
63 			get {
64 				return handle;
65 			}
66 		}
67 
GetArgs(int argc)68 		public string[] GetArgs (int argc)
69 		{
70 			int count = add_progname ? argc - 1 : argc;
71 			int idx = add_progname ? 1 : 0;
72 			string[] result = new string [count];
73 
74 			for (int i = 0; i < count; i++, idx++)
75 				result [i] = Marshaller.Utf8PtrToString (Marshal.ReadIntPtr (handle, idx * IntPtr.Size));
76 
77 			return result;
78 		}
79 	}
80 }
81 
82