forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleOps.cs
More file actions
654 lines (520 loc) · 23.2 KB
/
ModuleOps.cs
File metadata and controls
654 lines (520 loc) · 23.2 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_CTYPES
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Modules {
/// <summary>
/// Provides helper functions which need to be called from generated code to implement various
/// portions of modules.
/// </summary>
public static partial class ModuleOps {
public static IntPtr StringToHGlobalAnsi(string str) {
if (str == null) {
return IntPtr.Zero;
}
return Marshal.StringToHGlobalAnsi(str);
}
public static IntPtr StringToHGlobalUni(string str) {
if (str == null) {
return IntPtr.Zero;
}
return Marshal.StringToHGlobalUni(str);
}
public static object DoErrorCheck(object errCheckFunc, object result, object func, object[] arguments) {
return PythonCalls.Call(errCheckFunc, result, func, PythonTuple.Make(arguments));
}
public static object CreateMemoryHolder(IntPtr data, int size) {
var res = new MemoryHolder(size);
res.CopyFrom(data, new IntPtr(size));
return res;
}
public static object CreateNativeWrapper(PythonType type, object holder) {
Debug.Assert(holder is MemoryHolder);
CTypes.CData data = (CTypes.CData)type.CreateInstance(type.Context.SharedContext);
data.MemHolder = (MemoryHolder)holder;
return data;
}
public static object CreateCData(IntPtr dataAddress, PythonType type) {
CTypes.INativeType nativeType = (CTypes.INativeType)type;
CTypes.CData data = (CTypes.CData)type.CreateInstance(type.Context.SharedContext);
data.MemHolder = new MemoryHolder(nativeType.Size);
data.MemHolder.CopyFrom(dataAddress, new IntPtr(nativeType.Size));
return data;
}
public static object CreateCFunction(IntPtr address, PythonType type) {
return type.CreateInstance(type.Context.SharedContext, address);
}
public static CTypes.CData CheckSimpleCDataType(object o, object type) {
CTypes.SimpleCData res = o as CTypes.SimpleCData;
if (res == null && PythonOps.TryGetBoundAttr(o, "_as_parameter_", out object asParam)) {
res = asParam as CTypes.SimpleCData;
}
if (res != null && res.NativeType != type) {
throw PythonOps.TypeErrorForTypeMismatch(((PythonType)type).Name, o);
}
return res;
}
public static CTypes.CData/*!*/ CheckCDataType(object o, object type) {
CTypes.CData res = o as CTypes.CData;
if (res == null && PythonOps.TryGetBoundAttr(o, "_as_parameter_", out object asParam)) {
res = asParam as CTypes.CData;
}
bool valid = true;
// if we have an array, we can also send a pointer as long as the element types
// for the pointer and array are the same
if(res != null && res.NativeType is CTypes.ArrayType at) {
valid = ((type is CTypes.ArrayType t) && (t.ElementType == at.ElementType)) ||
((type is CTypes.PointerType p) && (p._type == at.ElementType));
}
if (res == null || !valid) {
throw ArgumentError(type, ((PythonType)type).Name, o);
}
return res;
}
public static IntPtr/*!*/ GetFunctionPointerValue(object o, object type) {
CTypes._CFuncPtr res = o as CTypes._CFuncPtr;
if (res == null && PythonOps.TryGetBoundAttr(o, "_as_parameter_", out object asParam)) {
res = asParam as CTypes._CFuncPtr;
}
if (res == null || res.NativeType != type) {
throw ArgumentError(type, ((PythonType)type).Name, o);
}
return res.addr;
}
public static CTypes.CData TryCheckCDataPointerType(object o, object type) {
CTypes.CData res = o as CTypes.CData;
if (res == null && PythonOps.TryGetBoundAttr(o, "_as_parameter_", out object asParam)) {
res = asParam as CTypes.CData;
}
bool valid = true;
// if we have an array, we can also send a pointer as long as the element types
// for the pointer and array are the same
if (res != null && res.NativeType is CTypes.ArrayType at) {
valid = ((type is CTypes.ArrayType t) && (t.ElementType == at.ElementType)) ||
((type is CTypes.PointerType p) && (p._type == at.ElementType));
}
if (res != null && !valid) {
throw ArgumentError(type, ((PythonType)((CTypes.PointerType)type)._type).Name, o);
}
return res;
}
public static CTypes._Array TryCheckCharArray(object o) {
if (o is CTypes._Array array) {
if (((CTypes.ArrayType)array.NativeType).ElementType is CTypes.SimpleType elemType && elemType._type == CTypes.SimpleTypeKind.Char) {
return array;
}
}
return null;
}
private static readonly byte[] FakeZeroLength = { 42 };
public static byte[] TryCheckBytes(object o) {
if (o is Bytes bytes) {
if (bytes.Count == 0) {
// OpCodes.Ldelema refuses to get address of empty array
// So we feed it with a fake one (cp34892)
return FakeZeroLength;
}
return bytes.UnsafeByteArray;
}
return null;
}
public static byte[] GetBytes(Bytes bytes) {
return bytes.UnsafeByteArray;
}
public static CTypes._Array TryCheckWCharArray(object o) {
if (o is CTypes._Array array) {
if (((CTypes.ArrayType)array.NativeType).ElementType is CTypes.SimpleType elemType && elemType._type == CTypes.SimpleTypeKind.WChar) {
return array;
}
}
return null;
}
public static object CreateSubclassInstance(object type, object instance) {
return PythonCalls.Call(type, instance);
}
public static void CallbackException(Exception e, CodeContext/*!*/ context) {
PythonContext pc = context.LanguageContext;
object stderr = pc.SystemStandardError;
PythonOps.PrintWithDest(context, stderr, pc.FormatException(e));
}
private static Exception ArgumentError(object type, string expected, object got) {
PythonContext pc = ((PythonType)type).Context;
return PythonExceptions.CreateThrowable(
(PythonType)pc.GetModuleState("ArgumentError"),
string.Format("expected {0}, got {1}", expected, PythonOps.GetPythonTypeName(got))
);
}
public static CTypes.CData CheckNativeArgument(object o, object type) {
if (o is CTypes.NativeArgument arg) {
if (((CTypes.PointerType)type)._type != DynamicHelpers.GetPythonType(arg._obj)) {
throw ArgumentError(type, ((PythonType)type).Name, o);
}
return arg._obj;
}
return null;
}
public static Bytes CharToBytes(byte c) {
return Bytes.FromByte(c);
}
public static string WCharToString(char c) {
return new string(c, 1);
}
public static char StringToChar(string s) {
return s[0];
}
public static string EnsureString(object o) {
if (!(o is string res)) {
throw PythonOps.TypeErrorForTypeMismatch("str", o);
}
return res;
}
public static bool CheckFunctionId(CTypes._CFuncPtr func, int id) {
return func.Id == id;
}
public static IntPtr GetWCharPointer(object value) {
if (value is string strVal) {
return Marshal.StringToCoTaskMemUni(strVal);
}
if (value == null) {
return IntPtr.Zero;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetWCharPointer(asParam);
}
throw PythonOps.TypeErrorForTypeMismatch("wchar pointer", value);
}
public static IntPtr GetBSTR(object value) {
if (value is string strVal) {
return Marshal.StringToBSTR(strVal);
}
if (value == null) {
return IntPtr.Zero;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetBSTR(asParam);
}
throw PythonOps.TypeErrorForTypeMismatch("BSTR", value);
}
public static IntPtr GetCharPointer(object value) {
if (value is Bytes bytes) {
var data = bytes.UnsafeByteArray;
var ptr = Marshal.AllocCoTaskMem(data.Length + 1);
Marshal.Copy(data, 0, ptr, data.Length);
Marshal.WriteByte(ptr, data.Length, 0);
return ptr;
}
if (value == null) {
return IntPtr.Zero;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetCharPointer(asParam);
}
throw PythonOps.TypeErrorForTypeMismatch("char pointer", value);
}
public static Bytes IntPtrToBytes(IntPtr ptr) {
// TODO: optimize this?
var str = Marshal.PtrToStringAnsi(ptr);
if (str is null) return null;
return Bytes.Make(str.MakeByteArray());
}
public static IntPtr GetPointer(object value) {
if (value == null) {
return IntPtr.Zero;
}
if (value is int iVal) {
if(iVal > int.MaxValue) {
iVal = -1;
}
return new IntPtr(iVal);
}
if (value is BigInteger bigVal) {
if(bigVal > long.MaxValue) {
bigVal = -1;
}
return new IntPtr((long)bigVal);
}
if (value is long lVal) {
return new IntPtr(lVal);
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetPointer(asParam);
}
if (value is CTypes.SimpleCData sd) {
CTypes.SimpleType simpType = (CTypes.SimpleType)sd.NativeType;
if (simpType._type == CTypes.SimpleTypeKind.WCharPointer ||
simpType._type == CTypes.SimpleTypeKind.CharPointer) {
return sd.UnsafeAddress;
} else if (simpType._type == CTypes.SimpleTypeKind.Pointer) {
return sd.MemHolder.ReadIntPtr(0);
}
}
if (value is CTypes._Array arr) {
return arr.UnsafeAddress;
}
if (value is CTypes._CFuncPtr func) {
return func.UnsafeAddress;
}
if (value is CTypes.Pointer pointer) {
return pointer.UnsafeAddress;
}
throw PythonOps.TypeErrorForTypeMismatch("pointer", value);
}
public static IntPtr GetInterfacePointer(IntPtr self, int offset) {
var vtable = Marshal.ReadIntPtr(self);
return Marshal.ReadIntPtr(vtable, offset * IntPtr.Size);
}
public static IntPtr GetObject(object value) {
GCHandle handle = GCHandle.Alloc(value);
// TODO: Need to free the handle at some point
return GCHandle.ToIntPtr(handle);
}
public static long GetSignedLongLong(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null) {
return res.Value;
}
if (value is BigInteger) {
return (long)(BigInteger)value;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetSignedLongLong(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("signed long long ", value);
}
public static long GetUnsignedLongLong(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null && res.Value >= 0) {
return res.Value;
}
if (value is BigInteger) {
return (long)(ulong)(BigInteger)value;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetUnsignedLongLong(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("unsigned long long", value);
}
public static double GetDouble(object value, object type) {
if (value is double) {
return (double)value;
} else if (value is float) {
return (float)value;
} else if (value is int) {
return (double)(int)value;
} else if (value is BigInteger) {
return (double)((BigInteger)value).ToFloat64();
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetDouble(asParam, type);
}
return Converter.ConvertToDouble(value);
}
public static float GetSingle(object value, object type) {
if (value is double) {
return (float)(double)value;
} else if (value is float) {
return (float)value;
} else if (value is int) {
return (float)(int)value;
} else if (value is BigInteger) {
return (float)((BigInteger)value).ToFloat64();
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetSingle(asParam, type);
}
return (float)Converter.ConvertToDouble(value);
}
public static long GetDoubleBits(object value) {
if (value is double) {
return BitConverter.ToInt64(BitConverter.GetBytes((double)value), 0);
} else if (value is float) {
return BitConverter.ToInt64(BitConverter.GetBytes((float)value), 0);
} else if (value is int) {
return BitConverter.ToInt64(BitConverter.GetBytes((double)(int)value), 0);
} else if (value is BigInteger) {
return BitConverter.ToInt64(BitConverter.GetBytes((double)((BigInteger)value).ToFloat64()), 0);
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetDoubleBits(asParam);
}
return BitConverter.ToInt64(BitConverter.GetBytes(Converter.ConvertToDouble(value)), 0);
}
public static int GetSingleBits(object value) {
if (value is double) {
return BitConverter.ToInt32(BitConverter.GetBytes((float)(double)value), 0);
} else if (value is float) {
return BitConverter.ToInt32(BitConverter.GetBytes((float)value), 0);
} else if (value is int) {
return BitConverter.ToInt32(BitConverter.GetBytes((float)(int)value), 0);
} else if (value is BigInteger) {
return BitConverter.ToInt32(BitConverter.GetBytes((float)((BigInteger)value).ToFloat64()), 0);
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetSingleBits(asParam);
}
return BitConverter.ToInt32(BitConverter.GetBytes((float)Converter.ConvertToDouble(value)), 0);
}
public static int GetSignedLong(object value, object type) {
if (value is int) {
return (int)value;
}
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null) {
return res.Value;
}
if (value is BigInteger && ((BigInteger)value).AsUInt32(out uint unsigned)) {
return (int)unsigned;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetSignedLong(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("signed long", value);
}
public static int GetUnsignedLong(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null) {
return res.Value;
}
if (value is BigInteger) {
if (((BigInteger)value).AsUInt32(out uint ures)) {
return (int)ures;
}
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetUnsignedLong(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("unsigned long", value);
}
public static int GetUnsignedInt(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null && res.Value >= 0) {
return res.Value;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetUnsignedInt(type, asParam);
}
throw PythonOps.TypeErrorForTypeMismatch("unsigned int", value);
}
public static int GetSignedInt(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null) {
return res.Value;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetSignedInt(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("signed int", value);
}
public static short GetUnsignedShort(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null) {
int iVal = res.Value;
if (iVal >= ushort.MinValue && iVal <= ushort.MaxValue) {
return (short)(ushort)iVal;
}
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetUnsignedShort(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("unsigned short", value);
}
public static short GetSignedShort(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null) {
int iVal = res.Value;
return (short)iVal;
} else if (value is BigInteger bigInt) {
return (short)(int)(bigInt & 0xffff);
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetSignedShort(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("signed short", value);
}
public static int GetVariantBool(object value, object type) {
return Converter.ConvertToBoolean(value) ? 1 : 0;
}
public static byte GetUnsignedByte(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null) {
return (byte)res.Value;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetUnsignedByte(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("unsigned byte", value);
}
public static byte GetSignedByte(object value, object type) {
int? res = Converter.ImplicitConvertToInt32(value);
if (res != null) {
int iVal = res.Value;
if (iVal >= sbyte.MinValue && iVal <= sbyte.MaxValue) {
return (byte)(sbyte)iVal;
}
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetSignedByte(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("signed byte", value);
}
public static byte GetBoolean(object value, object type) {
if (value is bool) {
return ((bool)value) ? (byte)1 : (byte)0;
} else if (value is int) {
return ((int)value) != 0 ? (byte)1 : (byte)0;
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetBoolean(asParam, type);
}
throw PythonOps.TypeErrorForTypeMismatch("bool", value);
}
public static byte GetChar(object value, object type) {
// TODO: .NET interop?
if (value is Bytes bytes && bytes.Count == 1) {
return ((IList<byte>)bytes)[0];
}
if (value is ByteArray bytearray && bytearray.Count == 1) {
return ((IList<byte>)bytearray)[0];
}
if (value is int i) {
try {
return checked((byte)i);
} catch (OverflowException) {
throw PythonOps.TypeError("one character bytes, bytearray or integer expected");
}
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetChar(asParam, type);
}
throw PythonOps.TypeError("one character bytes, bytearray or integer expected");
}
public static char GetWChar(object value, object type) {
if (value is string strVal) {
if (strVal.Length != 1) throw PythonOps.TypeError("one character unicode string expected");
return strVal[0];
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object asParam)) {
return GetWChar(asParam, type);
}
throw PythonOps.TypeError("unicode string expected instead of {0} instance", PythonOps.GetPythonTypeName(value));
}
public static object IntPtrToObject(IntPtr address) {
GCHandle handle = GCHandle.FromIntPtr(address);
object res = handle.Target;
handle.Free();
return res;
}
}
}
#endif