forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayType.cs
More file actions
409 lines (343 loc) · 15.7 KB
/
ArrayType.cs
File metadata and controls
409 lines (343 loc) · 15.7 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_NATIVE
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
#if CLR2
using Microsoft.Scripting.Math;
#else
using System.Numerics;
#endif
namespace IronPython.Modules {
/// <summary>
/// Provides support for interop with native code from Python code.
/// </summary>
public static partial class CTypes {
private static WeakDictionary<PythonType, Dictionary<int, ArrayType>> _arrayTypes = new WeakDictionary<PythonType, Dictionary<int, ArrayType>>();
/// <summary>
/// The meta class for ctypes array instances.
/// </summary>
[PythonType, PythonHidden]
public class ArrayType : PythonType, INativeType {
private int _length;
private INativeType _type;
public ArrayType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict)
: base(context, name, bases, dict) {
object len;
int iLen;
if (!dict.TryGetValue("_length_", out len) || !(len is int) || (iLen = (int)len) < 0) {
throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer");
}
object type;
if (!dict.TryGetValue("_type_", out type)) {
throw PythonOps.AttributeError("class must define a '_type_' attribute");
}
_length = iLen;
_type = (INativeType)type;
if (_type is SimpleType) {
SimpleType st = (SimpleType)_type;
if (st._type == SimpleTypeKind.Char) {
// TODO: (c_int * 2).value isn't working
SetCustomMember(context,
"value",
new ReflectedExtensionProperty(
new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetCharArrayValue")),
NameType.Property | NameType.Python
)
);
SetCustomMember(context,
"raw",
new ReflectedExtensionProperty(
new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayRaw")),
NameType.Property | NameType.Python
)
);
} else if (st._type == SimpleTypeKind.WChar) {
SetCustomMember(context,
"value",
new ReflectedExtensionProperty(
new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayValue")),
NameType.Property | NameType.Python
)
);
SetCustomMember(context,
"raw",
new ReflectedExtensionProperty(
new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayRaw")),
NameType.Property | NameType.Python
)
);
}
}
}
private ArrayType(Type underlyingSystemType)
: base(underlyingSystemType) {
}
public _Array from_address(CodeContext/*!*/ context, int ptr) {
_Array res = (_Array)CreateInstance(context);
res.SetAddress(new IntPtr(ptr));
return res;
}
public _Array from_address(CodeContext/*!*/ context, BigInteger ptr) {
_Array res = (_Array)CreateInstance(context);
res.SetAddress(new IntPtr((long)ptr));
return res;
}
public _Array from_buffer(ArrayModule.array array, [DefaultParameterValue(0)]int offset) {
ValidateArraySizes(array, offset, ((INativeType)this).Size);
_Array res = (_Array)CreateInstance(Context.SharedContext);
IntPtr addr = array.GetArrayAddress();
res._memHolder = new MemoryHolder(addr.Add(offset), ((INativeType)this).Size);
res._memHolder.AddObject("ffffffff", array);
return res;
}
public _Array from_buffer_copy(ArrayModule.array array, [DefaultParameterValue(0)]int offset) {
ValidateArraySizes(array, offset, ((INativeType)this).Size);
_Array res = (_Array)CreateInstance(Context.SharedContext);
res._memHolder = new MemoryHolder(((INativeType)this).Size);
res._memHolder.CopyFrom(array.GetArrayAddress().Add(offset), new IntPtr(((INativeType)this).Size));
GC.KeepAlive(array);
return res;
}
public _Array from_buffer_copy(Bytes array, [DefaultParameterValue(0)]int offset) {
ValidateArraySizes(array, offset, ((INativeType)this).Size);
_Array res = (_Array)CreateInstance(Context.SharedContext);
res._memHolder = new MemoryHolder(((INativeType)this).Size);
for (int i = 0; i < ((INativeType)this).Size; i++) {
res._memHolder.WriteByte(i, array._bytes[i]);
}
return res;
}
/// <summary>
/// Converts an object into a function call parameter.
/// </summary>
public object from_param(object obj) {
return null;
}
internal static PythonType MakeSystemType(Type underlyingSystemType) {
return PythonType.SetPythonType(underlyingSystemType, new ArrayType(underlyingSystemType));
}
public static ArrayType/*!*/ operator *(ArrayType type, int count) {
return MakeArrayType(type, count);
}
public static ArrayType/*!*/ operator *(int count, ArrayType type) {
return MakeArrayType(type, count);
}
#region INativeType Members
int INativeType.Size {
get {
return GetSize();
}
}
private int GetSize() {
return _length * _type.Size;
}
int INativeType.Alignment {
get {
return _type.Alignment;
}
}
object INativeType.GetValue(MemoryHolder owner, object readingFrom, int offset, bool raw) {
if (IsStringType) {
SimpleType st = (SimpleType)_type;
string str;
if (st._type == SimpleTypeKind.Char) {
str = owner.ReadAnsiString(offset, _length);
} else {
str = owner.ReadUnicodeString(offset, _length);
}
// remove any trailing nulls
for (int i = 0; i < str.Length; i++) {
if (str[i] == '\x00') {
return str.Substring(0, i);
}
}
return str;
}
_Array arr = (_Array)CreateInstance(Context.SharedContext);
arr._memHolder = new MemoryHolder(owner.UnsafeAddress.Add(offset), ((INativeType)this).Size, owner);
return arr;
}
internal string GetRawValue(MemoryHolder owner, int offset) {
Debug.Assert(IsStringType);
SimpleType st = (SimpleType)_type;
string str;
if (st._type == SimpleTypeKind.Char) {
str = owner.ReadAnsiString(offset, _length);
} else {
str = owner.ReadUnicodeString(offset, _length);
}
return str;
}
private bool IsStringType {
get {
SimpleType st = _type as SimpleType;
if (st != null) {
return st._type == SimpleTypeKind.WChar || st._type == SimpleTypeKind.Char;
}
return false;
}
}
object INativeType.SetValue(MemoryHolder address, int offset, object value) {
string str = value as string;
if (str != null) {
if (!IsStringType) {
throw PythonOps.TypeError("expected {0} instance, got str", Name);
} else if (str.Length > _length) {
throw PythonOps.ValueError("string too long ({0}, maximum length {1})", str.Length, _length);
}
WriteString(address, offset, str);
return null;
} else if (IsStringType) {
IList<object> objList = value as IList<object>;
if (objList != null) {
StringBuilder res = new StringBuilder(objList.Count);
foreach (object o in objList) {
res.Append(Converter.ConvertToChar(o));
}
WriteString(address, offset, res.ToString());
return null;
}
throw PythonOps.TypeError("expected string or Unicode object, {0} found", DynamicHelpers.GetPythonType(value).Name);
}
object[] arrArgs = value as object[];
if (arrArgs == null) {
PythonTuple pt = value as PythonTuple;
if (pt != null) {
arrArgs = pt._data;
}
}
if (arrArgs != null) {
if (arrArgs.Length > _length) {
throw PythonOps.RuntimeError("invalid index");
}
for (int i = 0; i < arrArgs.Length; i++) {
_type.SetValue(address, checked(offset + i * _type.Size), arrArgs[i]);
}
} else {
_Array arr = value as _Array;
if (arr != null && arr.NativeType == this) {
arr._memHolder.CopyTo(address, offset, ((INativeType)this).Size);
return arr._memHolder.EnsureObjects();
}
throw PythonOps.TypeError("unexpected {0} instance, got {1}", Name, DynamicHelpers.GetPythonType(value).Name);
}
return null;
}
private void WriteString(MemoryHolder address, int offset, string str) {
SimpleType st = (SimpleType)_type;
if (str.Length < _length) {
str = str + '\x00';
}
if (st._type == SimpleTypeKind.Char) {
address.WriteAnsiString(offset, str);
} else {
address.WriteUnicodeString(offset, str);
}
}
Type/*!*/ INativeType.GetNativeType() {
return typeof(IntPtr);
}
MarshalCleanup INativeType.EmitMarshalling(ILGenerator/*!*/ method, LocalOrArg argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
Type argumentType = argIndex.Type;
Label done = method.DefineLabel();
if (!argumentType.IsValueType) {
Label next = method.DefineLabel();
argIndex.Emit(method);
method.Emit(OpCodes.Ldnull);
method.Emit(OpCodes.Bne_Un, next);
method.Emit(OpCodes.Ldc_I4_0);
method.Emit(OpCodes.Conv_I);
method.Emit(OpCodes.Br, done);
method.MarkLabel(next);
}
argIndex.Emit(method);
if (argumentType.IsValueType) {
method.Emit(OpCodes.Box, argumentType);
}
constantPool.Add(this);
method.Emit(OpCodes.Ldarg, constantPoolArgument);
method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1);
method.Emit(OpCodes.Ldelem_Ref);
method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CheckCDataType"));
method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress"));
method.MarkLabel(done);
return null;
}
Type/*!*/ INativeType.GetPythonType() {
return ((INativeType)this).GetNativeType();
}
void INativeType.EmitReverseMarshalling(ILGenerator method, LocalOrArg value, List<object> constantPool, int constantPoolArgument) {
// TODO: Implement me
value.Emit(method);
}
#endregion
internal int Length {
get {
return _length;
}
}
internal INativeType ElementType {
get {
return _type;
}
}
string INativeType.TypeFormat {
get {
string size = "(" + Length;
INativeType elemType = ElementType;
while (elemType is ArrayType) {
size += "," + ((ArrayType)elemType).Length;
elemType = ((ArrayType)elemType).ElementType;
}
size += ")";
return size + elemType.TypeFormat;
}
}
}
private static ArrayType/*!*/ MakeArrayType(PythonType type, int count) {
if (count < 0) {
throw PythonOps.ValueError("cannot multiply ctype by negative number");
}
lock (_arrayTypes) {
ArrayType res;
Dictionary<int, ArrayType> countDict;
if (!_arrayTypes.TryGetValue(type, out countDict)) {
_arrayTypes[type] = countDict = new Dictionary<int, ArrayType>();
}
if (!countDict.TryGetValue(count, out res)) {
res = countDict[count] = new ArrayType(type.Context.SharedContext,
type.Name + "_Array_" + count,
PythonTuple.MakeTuple(Array),
PythonOps.MakeDictFromItems(new object[] { type, "_type_", count, "_length_" })
);
}
return res;
}
}
}
}
#endif