public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) {
CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob);
Array items = obj.inst as Array;
Type itemType = obj.inst.GetType().GetElementType();
int rank = items.Rank;
int index = 0;
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) {
index = (int)Runtime.PyInt_AsLong(idx);
if (Exceptions.ErrorOccurred()) {
return Exceptions.RaiseTypeError("invalid index value");
}
if (index < 0) {
index = items.Length + index;
}
try {
value = items.GetValue(index);
}
catch (IndexOutOfRangeException) {
Exceptions.SetError(Exceptions.IndexError,
"array index out of range"
);
return IntPtr.Zero;
}
return Converter.ToPython(items.GetValue(index), 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 IntPtr.Zero;
}
int count = Runtime.PyTuple_Size(idx);
Array args = Array.CreateInstance(typeof(Int32), count);
for (int i = 0; i < count; i++) {
IntPtr op = Runtime.PyTuple_GetItem(idx, i);
index = (int)Runtime.PyInt_AsLong(op);
if (Exceptions.ErrorOccurred()) {
return Exceptions.RaiseTypeError("invalid index value");
}
if (index < 0) {
index = items.GetLength(i) + index;
}
args.SetValue(index, i);
}
try {
value = items.GetValue((int[]) args);
}
catch (IndexOutOfRangeException) {
Exceptions.SetError(Exceptions.IndexError,
"array index out of range"
);
return IntPtr.Zero;
}
return Converter.ToPython(value, itemType);
}