forked from pythonnet/pythonnet
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathArrayObject.cs
More file actions
534 lines (455 loc) · 17.9 KB
/
ArrayObject.cs
File metadata and controls
534 lines (455 loc) · 17.9 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Python.Runtime
{
/// <summary>
/// Implements a Python type for managed arrays. This type is essentially
/// the same as a ClassObject, except that it provides sequence semantics
/// to support natural array usage (indexing) from Python.
/// </summary>
[Serializable]
internal sealed class ArrayObject : ClassBase
{
internal ArrayObject(Type tp) : base(tp)
{
}
internal override bool CanSubclass()
{
return false;
}
public static NewReference tp_new(BorrowedReference tp, BorrowedReference args, BorrowedReference kw)
{
if (kw != null)
{
return Exceptions.RaiseTypeError("array constructor takes no keyword arguments");
}
var self = (ArrayObject)GetManagedObject(tp)!;
if (!self.type.Valid)
{
return Exceptions.RaiseTypeError(self.type.DeletedMessage);
}
Type arrType = self.type.Value;
long[] dimensions = new long[Runtime.PyTuple_Size(args)];
if (dimensions.Length == 0)
{
return Exceptions.RaiseTypeError("array constructor requires at least one integer argument or an object convertible to array");
}
if (dimensions.Length != 1)
{
return CreateMultidimensional(arrType.GetElementType(), dimensions,
shapeTuple: args,
pyType: tp);
}
BorrowedReference op = Runtime.PyTuple_GetItem(args, 0);
// create single dimensional array
if (Runtime.PyInt_Check(op))
{
dimensions[0] = Runtime.PyLong_AsSignedSize_t(op);
if (dimensions[0] == -1 && Exceptions.ErrorOccurred())
{
Exceptions.Clear();
}
else
{
return NewInstance(arrType.GetElementType(), tp, dimensions);
}
}
object? result;
// this implements casting to Array[T]
if (!Converter.ToManaged(op, arrType, out result, true))
{
return default;
}
return CLRObject.GetReference(result!, tp);
}
static NewReference CreateMultidimensional(Type elementType, long[] dimensions, BorrowedReference shapeTuple, BorrowedReference pyType)
{
for (int dimIndex = 0; dimIndex < dimensions.Length; dimIndex++)
{
BorrowedReference dimObj = Runtime.PyTuple_GetItem(shapeTuple, dimIndex);
PythonException.ThrowIfIsNull(dimObj);
if (!Runtime.PyInt_Check(dimObj))
{
Exceptions.RaiseTypeError("array constructor expects integer dimensions");
return default;
}
dimensions[dimIndex] = Runtime.PyLong_AsSignedSize_t(dimObj);
if (dimensions[dimIndex] == -1 && Exceptions.ErrorOccurred())
{
Exceptions.RaiseTypeError("array constructor expects integer dimensions");
return default;
}
}
return NewInstance(elementType, pyType, dimensions);
}
static NewReference NewInstance(Type elementType, BorrowedReference arrayPyType, long[] dimensions)
{
for (int dim = 0; dim < dimensions.Length; dim++)
{
if (dimensions[dim] < 0)
{
Exceptions.SetError(Exceptions.ValueError, $"Non-negative number required (dims[{dim}])");
return default;
}
}
object result;
try
{
result = Array.CreateInstance(elementType, dimensions);
}
catch (ArgumentException badArgument)
{
Exceptions.SetError(Exceptions.ValueError, badArgument.Message);
return default;
}
catch (OverflowException overflow)
{
Exceptions.SetError(overflow);
return default;
}
catch (NotSupportedException notSupported)
{
Exceptions.SetError(notSupported);
return default;
}
catch (OutOfMemoryException oom)
{
Exceptions.SetError(Exceptions.MemoryError, oom.Message);
return default;
}
return CLRObject.GetReference(result, arrayPyType);
}
/// <summary><
10BC0
/div>
/// Implements __getitem__ for array types.
/// </summary>
public static NewReference mp_subscript(BorrowedReference ob, BorrowedReference idx)
{
var obj = (CLRObject)GetManagedObject(ob)!;
var arrObj = (ArrayObject)GetManagedObject(Runtime.PyObject_TYPE(ob))!;
if (!arrObj.type.Valid)
{
return Exceptions.RaiseTypeError(arrObj.type.DeletedMessage);
}
var items = (Array)obj.inst;
Type itemType = arrObj.type.Value.GetElementType();
int rank = items.Rank;
long index;
object value;
// Note that CLR 1.0 only supports int indexes - methods to
// support long indices were introduced in 1.1. We could
// support long indices automatically, but given that long
// indices are not backward compatible and a relative edge
// case, we won't bother for now.
// Single-dimensional arrays are the most common case and are
// cheaper to deal with than multi-dimensional, so check first.
if (rank == 1)
{
if (!Runtime.PyInt_Check(idx))
{
return RaiseIndexMustBeIntegerError(idx);
}
index = Runtime.PyLong_AsSignedSize_t(idx);
if (index == -1 && Exceptions.ErrorOccurred())
{
return Exceptions.RaiseTypeError("invalid index value");
}
if (index < 0)
{
index = items.LongLength + index;
}
if (index < 0 || index >= items.LongLength)
{
Exceptions.SetError(Exceptions.IndexError, "array index out of range");
return default;
}
value = items.GetValue(index);
return Converter.ToPython(value, itemType);
}
// Multi-dimensional arrays can be indexed a la: list[1, 2, 3].
if (!Runtime.PyTuple_Check(idx))
{
Exceptions.SetError(Exceptions.TypeError, "invalid index value");
return default;
}
var count = Runtime.PyTuple_Size(idx);
long[] indices = new long[count];
for (int dimension = 0; dimension < count; dimension++)
{
BorrowedReference op = Runtime.PyTuple_GetItem(idx, dimension);
if (!Runtime.PyInt_Check(op))
{
return RaiseIndexMustBeIntegerError(op);
}
index = Runtime.PyLong_AsSignedSize_t(op);
if (index == -1 && Exceptions.ErrorOccurred())
{
return Exceptions.RaiseTypeError("invalid index value");
}
long len = items.GetLongLength(dimension);
if (index < 0)
{
index = len + index;
}
if (index < 0 || index >= len)
{
Exceptions.SetError(Exceptions.IndexError, "array index out of range");
return default;
}
indices[dimension] = index;
}
value = items.GetValue(indices);
return Converter.ToPython(value, itemType);
}
/// <summary>
/// Implements __setitem__ for array types.
/// </summary>
public static int mp_ass_subscript(BorrowedReference ob, BorrowedReference idx, BorrowedReference v)
{
var obj = (CLRObject)GetManagedObject(ob)!;
var items = (Array)obj.inst;
Type itemType = obj.inst.GetType().GetElementType();
int rank = items.Rank;
long index;
object? value;
if (items.IsReadOnly)
{
Exceptions.RaiseTypeError("array is read-only");
return -1;
}
if (!Converter.ToManaged(v, itemType, out value, true))
{
return -1;
}
if (rank == 1)
{
if (!Runtime.PyInt_Check(idx))
{
RaiseIndexMustBeIntegerError(idx);
return -1;
}
index = Runtime.PyLong_AsSignedSize_t(idx);
if (index == -1 && Exceptions.ErrorOccurred())
{
Exceptions.RaiseTypeError("invalid index value");
return -1;
}
if (index < 0)
{
index = items.LongLength + index;
}
if (index < 0 || index >= items.LongLength)
{
Exceptions.SetError(Exceptions.IndexError, "array index out of range");
return -1;
}
items.SetValue(value, index);
return 0;
}
if (!Runtime.PyTuple_Check(idx))
{
Exceptions.RaiseTypeError("invalid index value");
return -1;
}
var count = Runtime.PyTuple_Size(idx);
long[] indices = new long[count];
for (int dimension = 0; dimension < count; dimension++)
{
BorrowedReference op = Runtime.PyTuple_GetItem(idx, dimension);
if (!Runtime.PyInt_Check(op))
{
RaiseIndexMustBeIntegerError(op);
return -1;
}
index = Runtime.PyLong_AsSignedSize_t(op);
if (index == -1 && Exceptions.ErrorOccurred())
{
Exceptions.RaiseTypeError("invalid index value");
return -1;
}
long len = items.GetLongLength(dimension);
if (index < 0)
{
index = len + index;
}
if (index < 0 || index >= len)
{
Exceptions.SetError(Exceptions.IndexError, "array index out of range");
return -1;
}
indices[dimension] = index;
}
items.SetValue(value, indices);
return 0;
}
private static NewReference RaiseIndexMustBeIntegerError(BorrowedReference idx)
{
string tpName = Runtime.PyObject_GetTypeName(idx);
return Exceptions.RaiseTypeError($"array index has type {tpName}, expected an integer");
}
/// <summary>
/// Implements __contains__ for array types.
/// </summary>
public static int sq_contains(BorrowedReference ob, BorrowedReference v)
{
var obj = (CLRObject)GetManagedObject(ob)!;
Type itemType = obj.inst.GetType().GetElementType();
var items = (IList)obj.inst;
object? value;
if (!Converter.ToManaged(v, itemType, out value, false))
{
return 0;
}
if (items.Contains(value))
{
return 1;
}
return 0;
}
#region Buffer protocol
static int GetBuffer(BorrowedReference obj, out Py_buffer buffer, PyBUF flags)
{
buffer = default;
if (flags == PyBUF.SIMPLE)
{
Exceptions.SetError(Exceptions.BufferError, "SIMPLE not implemented");
return -1;
}
if ((flags & PyBUF.F_CONTIGUOUS) == PyBUF.F_CONTIGUOUS)
{
Exceptions.SetError(Exceptions.BufferError, "only C-contiguous supported");
return -1;
}
var self = (Array)((CLRObject)GetManagedObject(obj)!).inst;
Type itemType = self.GetType().GetElementType();
bool formatRequested = (flags & PyBUF.FORMATS) != 0;
string? format = GetFormat(itemType);
if (formatRequested && format is null)
{
Exceptions.SetError(Exceptions.BufferError, "unsupported element type: " + itemType.Name);
return -1;
}
GCHandle gcHandle;
try
{
gcHandle = GCHandle.Alloc(self, GCHandleType.Pinned);
} catch (ArgumentException ex)
{
Exceptions.SetError(Exceptions.BufferError, ex.Message);
return -1;
}
int itemSize = Marshal.SizeOf(itemType);
IntPtr[] shape = GetShape(self);
IntPtr[] strides = GetStrides(shape, itemSize);
buffer = new Py_buffer
{
buf = gcHandle.AddrOfPinnedObject(),
obj = new NewReference(obj).DangerousMoveToPointer(),
len = (IntPtr)(self.LongLength*itemSize),
itemsize = (IntPtr)itemSize,
_readonly = false,
ndim = self.Rank,
format = format,
shape = ToUnmanaged(shape),
strides = (flags & PyBUF.STRIDES) == PyBUF.STRIDES ? ToUnmanaged(strides) : IntPtr.Zero,
suboffsets = IntPtr.Zero,
_internal = (IntPtr)gcHandle,
};
return 0;
}
static void ReleaseBuffer(BorrowedReference obj, ref Py_buffer buffer)
{
if (buffer._internal == IntPtr.Zero) return;
UnmanagedFree(ref buffer.shape);
UnmanagedFree(ref buffer.strides);
UnmanagedFree(ref buffer.suboffsets);
// TODO: decref buffer.obj?
var gcHandle = (GCHandle)buffer._internal;
gcHandle.Free();
buffer._internal = IntPtr.Zero;
}
static IntPtr[] GetStrides(IntPtr[] shape, long itemSize)
{
var result = new IntPtr[shape.Length];
result[shape.Length - 1] = new IntPtr(itemSize);
for (int dim = shape.Length - 2; dim >= 0; dim--)
{
itemSize *= shape[dim + 1].ToInt64();
result[dim] = new IntPtr(itemSize);
}
return result;
}
static IntPtr[] GetShape(Array array)
{
var result = new IntPtr[array.Rank];
for (int i = 0; i < result.Length; i++)
result[i] = (IntPtr)array.GetLongLength(i);
return result;
}
static void UnmanagedFree(ref IntPtr address)
{
if (address == IntPtr.Zero) return;
Marshal.FreeHGlobal(address);
address = IntPtr.Zero;
}
static unsafe IntPtr ToUnmanaged<T>(T[] array) where T : unmanaged
{
IntPtr result = Marshal.AllocHGlobal(checked(Marshal.SizeOf(typeof(T)) * array.Length));
fixed (T* ptr = array)
{
var @out = (T*)result;
for (int i = 0; i < array.Length; i++)
@out[i] = ptr[i];
}
return result;
}
static readonly Dictionary<Type, string> ItemFormats = new Dictionary<Type, string>
{
[typeof(byte)] = "B",
[typeof(sbyte)] = "b",
[typeof(bool)] = "?",
[typeof(short)] = "h",
[typeof(ushort)] = "H",
// see https://github.com/pybind/pybind11/issues/1908#issuecomment-658358767
[typeof(int)] = "i",
[typeof(uint)] = "I",
[typeof(long)] = "q",
[typeof(ulong)] = "Q",
[typeof(IntPtr)] = "n",
[typeof(UIntPtr)] = "N",
// TODO: half = "e"
[typeof(float)] = "f",
[typeof(double)] = "d",
};
static string? GetFormat(Type elementType)
=> ItemFormats.TryGetValue(elementType, out string result) ? result : null;
static readonly GetBufferProc getBufferProc = GetBuffer;
static readonly ReleaseBufferProc releaseBufferProc = ReleaseBuffer;
static readonly IntPtr BufferProcsAddress = AllocateBufferProcs();
static IntPtr AllocateBufferProcs()
{
var procs = new PyBufferProcs
{
Get = Marshal.GetFunctionPointerForDelegate(getBufferProc),
Release = Marshal.GetFunctionPointerForDelegate(releaseBufferProc),
};
IntPtr result = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PyBufferProcs)));
Marshal.StructureToPtr(procs, result, fDeleteOld: false);
return result;
}
#endregion
/// <summary>
/// <see cref="TypeManager.InitializeSlots(IntPtr, Type, SlotsHolder)"/>
/// </summary>
public static void InitializeSlots(PyType type, ISet<string> initialized, SlotsHolder slotsHolder)
{
if (initialized.Add(nameof(TypeOffset.tp_as_buffer)))
{
// TODO: only for unmanaged arrays
int offset = TypeOffset.GetSlotOffset(nameof(TypeOffset.tp_as_buffer));
Util.WriteIntPtr(type, offset, BufferProcsAddress);
}
}
}
}