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
375 lines (313 loc) · 15.1 KB
/
ArrayType.cs
File metadata and controls
375 lines (313 loc) · 15.1 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
// 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.Reflection.Emit;
using System.Runtime.InteropServices;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting.Utils;
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) {
// TODO: is using TryGetBoundAttr the proper way to check the base types? similarly on the _type_ check
if (!dict.TryGetValue("_length_", out object len) && !TryGetBoundAttr(context, this, "_length_", out len)) {
throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer");
}
int iLen = len switch {
BigInteger bi => checked((int)bi),
int i => i,
_ => throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer"),
};
if (iLen < 0) throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer"); // TODO: ValueError with 3.8
object type;
if (!dict.TryGetValue("_type_", out type) && !TryGetBoundAttr(context, this, "_type_", out type)) {
throw PythonOps.AttributeError("class must define a '_type_' attribute");
}
_length = iLen;
_type = (INativeType)type;
if (_type is SimpleType st) {
if (st._type == SimpleTypeKind.Char) {
SetCustomMember(context,
"value",
new ReflectedExtensionProperty(
new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod(nameof(CTypes.GetCharArrayValue))),
NameType.Property | NameType.Python
)
);
SetCustomMember(context,
"raw",
new ReflectedExtensionProperty(
new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod(nameof(CTypes.GetCharArrayRaw))),
NameType.Property | NameType.Python
)
);
} else if (st._type == SimpleTypeKind.WChar) {
SetCustomMember(context,
"value",
new ReflectedExtensionProperty(
new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod(nameof(CTypes.GetWCharArrayValue))),
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(CodeContext/*!*/ context, object/*?*/ data, int offset = 0) {
_Array res = (_Array)CreateInstance(context);
res.InitializeFromBuffer(data, offset, ((INativeType)this).Size);
return res;
}
public _Array from_buffer_copy(CodeContext/*!*/ context, object/*?*/ data, int offset = 0) {
_Array res = (_Array)CreateInstance(context);
res.InitializeFromBufferCopy(data, offset, ((INativeType)this).Size);
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 (_type is SimpleType st) {
if (st._type == SimpleTypeKind.Char) {
var str = owner.ReadBytes(offset, _length);
// remove any trailing nulls
for (int i = 0; i < str.Count; i++) {
if (str[i] == 0) {
return new Bytes(str.Substring(0, i));
}
}
return str;
}
if (st._type == SimpleTypeKind.WChar) {
string 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 object GetRawValue(MemoryHolder owner, int offset) {
Debug.Assert(_type is SimpleType st && st._type == SimpleTypeKind.Char);
return owner.ReadBytes(offset, _length);
}
internal void SetRawValue(MemoryHolder owner, int offset, object value) {
Debug.Assert(_type is SimpleType st && st._type == SimpleTypeKind.Char);
if (value is IBufferProtocol bufferProtocol) {
var buffer = bufferProtocol.GetBuffer();
var span = buffer.AsReadOnlySpan();
if (span.Length > _length) {
throw PythonOps.ValueError("byte string too long ({0}, maximum length {1})", span.Length, _length);
}
owner.WriteSpan(offset, span);
return;
}
throw PythonOps.TypeErrorForBytesLikeTypeMismatch(value);
}
object INativeType.SetValue(MemoryHolder address, int offset, object value) {
if (_type is SimpleType st) {
if (st._type == SimpleTypeKind.Char) {
if (value is Bytes bytes) {
if (bytes.Count > _length) {
throw PythonOps.ValueError("byte string too long ({0}, maximum length {1})", bytes.Count, _length);
}
WriteBytes(address, offset, bytes);
return null;
}
throw PythonOps.TypeError("expected bytes, {0} found", PythonOps.GetPythonTypeName(value));
}
if (st._type == SimpleTypeKind.WChar) {
if (value is string str) {
if (str.Length > _length) {
throw PythonOps.ValueError("string too long ({0}, maximum length {1})", str.Length, _length);
}
WriteString(address, offset, str);
return null;
}
throw PythonOps.TypeError("unicode string expected instead of {0} instance", PythonOps.GetPythonTypeName(value));
}
}
object[] arrArgs = value as object[];
if (arrArgs == null) {
if (value is PythonTuple pt) {
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 {
if (value is _Array arr && arr.NativeType == this) {
arr.MemHolder.CopyTo(address, offset, ((INativeType)this).Size);
return arr.MemHolder.EnsureObjects();
}
throw PythonOps.TypeError("unexpected {0} instance, got {1}", Name, PythonOps.GetPythonTypeName(value));
}
return null;
}
private void WriteBytes(MemoryHolder address, int offset, Bytes bytes) {
SimpleType st = (SimpleType)_type;
Debug.Assert(st._type == SimpleTypeKind.Char && bytes.Count <= _length);
address.WriteSpan(offset, bytes.AsSpan());
if (bytes.Count < _length) {
address.WriteByte(checked(offset + bytes.Count), 0);
}
}
private void WriteString(MemoryHolder address, int offset, string str) {
SimpleType st = (SimpleType)_type;
Debug.Assert(st._type == SimpleTypeKind.WChar && str.Length <= _length);
if (str.Length < _length) {
str = str + '\x00';
}
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(nameof(ModuleOps.CheckCDataType)));
method.Emit(OpCodes.Call, typeof(CData).GetProperty(nameof(CData.UnsafeAddress)).GetGetMethod());
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 {
return _type.TypeFormat;
}
}
internal string ShapeAndFormatRepr() {
string size = "(" + Length;
INativeType elemType = _type;
while (elemType is ArrayType arrayType) {
size += "," + arrayType.Length;
elemType = arrayType.ElementType;
}
size += ")";
return size + _type.TypeFormat;
}
}
private static ArrayType/*!*/ MakeArrayType(PythonType type, int count) {
if (count < 0) {
throw PythonOps.ValueError("cannot multiply ctype by negative number");
}
lock (_arrayTypes) {
if (!_arrayTypes.TryGetValue(type, out Dictionary<int, ArrayType> countDict)) {
_arrayTypes[type] = countDict = new Dictionary<int, ArrayType>();
}
if (!countDict.TryGetValue(count, out ArrayType 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