Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CdeclFunction.cs « Mono.Unix « Mono.Posix « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8059fc081f9ea734eab3bafc4bf3af4b341a2623 (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//
// Mono.Unix/CdeclFunction.cs
//
// Authors:
//   Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;

namespace Mono.Unix {

	// This class represents a single unmanaged function with "cdecl" calling
	// convention -- that is, it can accept a variable number of arguments which
	// are passed on the runtime stack.
	//
	// To use, create an instance:
	//
	//    CdeclFunction printf = new CdeclFunction ("the library", 
	//        "the function name", /* optional */ typeof (ReturnType));
	//
	// Then call the Invoke method with the appropriate number of arguments:
	//
	// 		printf.Invoke (new object[]{"hello, %s\n", "world!"});
	//
	// In the background a P/Invoke definition for the method with the
	// requested argument types will be generated and invoked, invoking the
	// unmanaged function.  The generated methods are cached, so that subsequent
	// calls with the same argument list do not generate new code, speeding up
	// the call sequence.
	//
	// This class is intended to be thread-safe.
	public sealed class CdeclFunction
	{
		// The readonly fields (1) shouldn't be modified, and (2) should only be
		// used when `overloads' is locked.
		private readonly string library;
		private readonly string method;
		private readonly Type returnType;
		private readonly AssemblyName assemblyName;
		private readonly AssemblyBuilder assemblyBuilder;
		private readonly ModuleBuilder moduleBuilder;

		private Hashtable overloads;

		public CdeclFunction (string library, string method)
			: this (library, method, typeof(void))
		{
		}

		public CdeclFunction (string library, string method, Type returnType)
		{
			this.library = library;
			this.method = method;
			this.returnType = returnType;
			this.overloads = new Hashtable ();
			this.assemblyName = new AssemblyName ();
			this.assemblyName.Name = "Mono.Posix.Imports." + library;
			this.assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (
					assemblyName, AssemblyBuilderAccess.Run);
			this.moduleBuilder = assemblyBuilder.DefineDynamicModule (assemblyName.Name);
		}

		public object Invoke (object[] parameters)
		{
			Type[] parameterTypes = GetParameterTypes (parameters);
			MethodInfo m = CreateMethod (parameterTypes);
			return m.Invoke (null, parameters);
		}

		private MethodInfo CreateMethod (Type[] parameterTypes)
		{
			string typeName = GetTypeName (parameterTypes);

			lock (overloads) {
				MethodInfo mi = (MethodInfo) overloads [typeName];

				if (mi != null) {
					return mi;
				}

				TypeBuilder tb = CreateType (typeName);
				MethodBuilder mb = tb.DefinePInvokeMethod (
						method, 
						library, 
						MethodAttributes.PinvokeImpl | MethodAttributes.Static | MethodAttributes.Public,
						CallingConventions.Standard, 
						returnType, 
						parameterTypes, 
						CallingConvention.Cdecl,
						CharSet.Ansi);
				mi = tb.CreateType ().GetMethod (method);
				overloads.Add (typeName, mi);
				return mi;
			}
		}

		private TypeBuilder CreateType (string typeName)
		{
			return moduleBuilder.DefineType (typeName, TypeAttributes.Public);
		}

		private static Type GetMarshalType (Type t)
		{
			switch (Type.GetTypeCode (t)) {
				// types < sizeof(int) are marshaled as ints
				case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: 
				case TypeCode.Int16: case TypeCode.Int32: 
					return typeof(int);
				case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32:
					return typeof(uint);
				case TypeCode.Int64:
					return typeof(long);
				case TypeCode.UInt64:
					return typeof(ulong);
				case TypeCode.Single: case TypeCode.Double:
					return typeof(double);
				default:
					return t;
			}
		}

		private string GetTypeName (Type[] parameterTypes)
		{
			StringBuilder sb = new StringBuilder ();

			sb.Append ("[").Append (library).Append ("] ").Append (method);
			sb.Append ("(");

			if (parameterTypes.Length > 0)
				sb.Append (parameterTypes [0]);
			for (int i = 1; i < parameterTypes.Length; ++i)
				sb.Append (",").Append (parameterTypes [i]);

			sb.Append (") : ").Append (returnType.FullName);

			return sb.ToString ();
		}

		private static Type[] GetParameterTypes (object[] parameters)
		{
			Type[] parameterTypes = new Type [parameters.Length];
			for (int i = 0; i < parameters.Length; ++i)
				parameterTypes [i] = GetMarshalType (parameters [i].GetType ());
			return parameterTypes;
		}
	}
}