PyObject_CallObject() private method

private PyObject_CallObject ( IntPtr pointer, IntPtr args ) : IntPtr
pointer IntPtr
args IntPtr
return IntPtr
Ejemplo n.º 1
0
        static void SetupImportHook()
        {
            // Create the import hook module
            var import_hook_module = Runtime.PyModule_New("clr.loader");

            // Run the python code to create the module's classes.
            var builtins = Runtime.PyEval_GetBuiltins();
            var exec     = Runtime.PyDict_GetItemString(builtins, "exec");

            using var args = NewReference.DangerousFromPointer(Runtime.PyTuple_New(2));

            var codeStr = NewReference.DangerousFromPointer(Runtime.PyString_FromString(LoaderCode));

            Runtime.PyTuple_SetItem(args, 0, codeStr);
            var mod_dict = Runtime.PyModule_GetDict(import_hook_module);

            // reference not stolen due to overload incref'ing for us.
            Runtime.PyTuple_SetItem(args, 1, mod_dict);
            Runtime.PyObject_Call(exec, args, default).Dispose();
            // Set as a sub-module of clr.
            if (Runtime.PyModule_AddObject(ClrModuleReference, "loader", import_hook_module.DangerousGetAddress()) != 0)
            {
                Runtime.XDecref(import_hook_module.DangerousGetAddress());
                throw PythonException.ThrowLastAsClrException();
            }

            // Finally, add the hook to the meta path
            var findercls      = Runtime.PyDict_GetItemString(mod_dict, "DotNetFinder");
            var finderCtorArgs = NewReference.DangerousFromPointer(Runtime.PyTuple_New(0));
            var finder_inst    = Runtime.PyObject_CallObject(findercls, finderCtorArgs);
            var metapath       = Runtime.PySys_GetObject("meta_path");

            Runtime.PyList_Append(metapath, finder_inst);
        }
Ejemplo n.º 2
0
        //====================================================================
        // helper methods for raising warnings
        //====================================================================

        /// <summary>
        /// Alias for Python's warnings.warn() function.
        /// </summary>
        public static void warn(string message, IntPtr exception, int stacklevel)
        {
            if (exception == IntPtr.Zero ||
                (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1))
            {
                Exceptions.RaiseTypeError("Invalid exception");
            }

            Runtime.XIncref(warnings_module);
            IntPtr warn = Runtime.PyObject_GetAttrString(warnings_module, "warn");

            Runtime.XDecref(warnings_module);
            Exceptions.ErrorCheck(warn);

            IntPtr args = Runtime.PyTuple_New(3);
            IntPtr msg  = Runtime.PyString_FromString(message);

            Runtime.XIncref(exception); // PyTuple_SetItem steals a reference
            IntPtr level = Runtime.PyInt_FromInt32(stacklevel);

            Runtime.PyTuple_SetItem(args, 0, msg);
            Runtime.PyTuple_SetItem(args, 1, exception);
            Runtime.PyTuple_SetItem(args, 2, level);

            IntPtr result = Runtime.PyObject_CallObject(warn, args);

            Exceptions.ErrorCheck(result);

            Runtime.XDecref(warn);
            Runtime.XDecref(result);
            Runtime.XDecref(args);
        }
Ejemplo n.º 3
0
        /// <remarks>
        /// Unlike <see cref="ToManaged(BorrowedReference, Type, out object?, bool)"/>,
        /// this method does not have a <c>setError</c> parameter, because it should
        /// only be called after <see cref="ToManaged(BorrowedReference, Type, out object?, bool)"/>.
        /// </remarks>
        internal static bool ToManagedExplicit(BorrowedReference value, Type obType,
                                               out object?result)
        {
            result = null;

            // this method would potentially clean any existing error resulting in information loss
            Debug.Assert(Runtime.PyErr_Occurred() == null);

            string?converterName =
                IsInteger(obType) ? "__int__"
                : IsFloatingNumber(obType) ? "__float__"
                : null;

            if (converterName is null)
            {
                return(false);
            }

            Debug.Assert(obType.IsPrimitive);

            using var converter = Runtime.PyObject_GetAttrString(value, converterName);
            if (converter.IsNull())
            {
                Exceptions.Clear();
                return(false);
            }

            using var explicitlyCoerced = Runtime.PyObject_CallObject(converter.Borrow(), BorrowedReference.Null);
            if (explicitlyCoerced.IsNull())
            {
                Exceptions.Clear();
                return(false);
            }
            return(ToPrimitive(explicitlyCoerced.Borrow(), obType, out result, false));
        }
Ejemplo n.º 4
0
        static void SetupImportHook()
        {
            // Create the import hook module
            using var import_hook_module = Runtime.PyModule_New("clr.loader");
            BorrowedReference mod_dict = Runtime.PyModule_GetDict(import_hook_module.BorrowOrThrow());

            Debug.Assert(mod_dict != null);

            // Run the python code to create the module's classes.
            var builtins = Runtime.PyEval_GetBuiltins();
            var exec     = Runtime.PyDict_GetItemString(builtins, "exec");

            using var args = Runtime.PyTuple_New(2);
            PythonException.ThrowIfIsNull(args);
            using var codeStr = Runtime.PyString_FromString(LoaderCode);
            Runtime.PyTuple_SetItem(args.Borrow(), 0, codeStr.StealOrThrow());

            // reference not stolen due to overload incref'ing for us.
            Runtime.PyTuple_SetItem(args.Borrow(), 1, mod_dict);
            Runtime.PyObject_Call(exec, args.Borrow(), default).Dispose();
            // Set as a sub-module of clr.
            if (Runtime.PyModule_AddObject(ClrModuleReference, "loader", import_hook_module.Steal()) != 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }

            // Finally, add the hook to the meta path
            var findercls = Runtime.PyDict_GetItemString(mod_dict, "DotNetFinder");

            using var finderCtorArgs = Runtime.PyTuple_New(0);
            using var finder_inst    = Runtime.PyObject_CallObject(findercls, finderCtorArgs.Borrow());
            var metapath = Runtime.PySys_GetObject("meta_path");

            PythonException.ThrowIfIsNotZero(Runtime.PyList_Append(metapath, finder_inst.BorrowOrThrow()));
        }
Ejemplo n.º 5
0
        private static IntPtr TzInfo(DateTimeKind kind)
        {
            if (kind == DateTimeKind.Unspecified)
            {
                return(Runtime.PyNone);
            }
            var    offset     = kind == DateTimeKind.Local ? DateTimeOffset.Now.Offset : TimeSpan.Zero;
            IntPtr tzInfoArgs = Runtime.PyTuple_New(2);

            Runtime.PyTuple_SetItem(tzInfoArgs, 0, Runtime.PyFloat_FromDouble(offset.Hours));
            Runtime.PyTuple_SetItem(tzInfoArgs, 1, Runtime.PyFloat_FromDouble(offset.Minutes));
            return(Runtime.PyObject_CallObject(tzInfoCtor, tzInfoArgs));
        }
Ejemplo n.º 6
0
            public override ValueType Execute(ValueType arg)
            {
                var module = (IntPtr)arg;
                using (Py.GIL())
                {
                    var test_obj_call = PyRuntime.PyObject_GetAttrString(module, "test_obj_call");
                    PythonException.ThrowIfIsNull(test_obj_call);
                    var args = PyRuntime.PyTuple_New(0);
                    var res = PyRuntime.PyObject_CallObject(test_obj_call, args);
                    PythonException.ThrowIfIsNull(res);

                    PyRuntime.XDecref(args);
                    PyRuntime.XDecref(res);
                }
                return 0;
            }
Ejemplo n.º 7
0
        //====================================================================
        // helper methods for raising warnings
        //====================================================================

        /// <summary>
        /// Alias for Python's warnings.warn() function.
        /// </summary>
        public static void warn(string message, BorrowedReference exception, int stacklevel)
        {
            if (exception == null ||
                (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1))
            {
                Exceptions.RaiseTypeError("Invalid exception");
            }

            using var warn = Runtime.PyObject_GetAttrString(warnings_module.obj, "warn");
            Exceptions.ErrorCheck(warn.Borrow());

            using var argsTemp = Runtime.PyTuple_New(3);
            BorrowedReference args = argsTemp.BorrowOrThrow();

            using var msg = Runtime.PyString_FromString(message);
            Runtime.PyTuple_SetItem(args, 0, msg.StealOrThrow());
            Runtime.PyTuple_SetItem(args, 1, exception);

            using var level = Runtime.PyInt_FromInt32(stacklevel);
            Runtime.PyTuple_SetItem(args, 2, level.StealOrThrow());

            using var result = Runtime.PyObject_CallObject(warn.Borrow(), args);
            Exceptions.ErrorCheck(result.Borrow());
        }
Ejemplo n.º 8
0
        internal static IntPtr ToPython(object value, Type type)
        {
            if (value is PyObject)
            {
                IntPtr handle = ((PyObject)value).Handle;
                Runtime.XIncref(handle);
                return(handle);
            }
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.XIncref(result);
                return(result);
            }

            if (value is IList && value.GetType().IsGenericType)
            {
                using (var resultlist = new PyList())
                {
                    foreach (object o in (IEnumerable)value)
                    {
                        using (var p = new PyObject(ToPython(o, o?.GetType())))
                        {
                            resultlist.Append(p);
                        }
                    }
                    Runtime.XIncref(resultlist.Handle);
                    return(resultlist.Handle);
                }
            }

            // it the type is a python subclass of a managed type then return the
            // underlying python object rather than construct a new wrapper object.
            var pyderived = value as IPythonDerivedType;

            if (null != pyderived)
            {
                return(ClassDerivedObject.ToPython(pyderived));
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
            case TypeCode.Object:
                if (value is TimeSpan)
                {
                    var timespan = (TimeSpan)value;

                    IntPtr timeSpanArgs = Runtime.PyTuple_New(1);
                    Runtime.PyTuple_SetItem(timeSpanArgs, 0, Runtime.PyFloat_FromDouble(timespan.TotalDays));
                    return(Runtime.PyObject_CallObject(timeSpanCtor, timeSpanArgs));
                }
                return(CLRObject.GetInstHandle(value, type));

            case TypeCode.String:
                return(Runtime.PyUnicode_FromString((string)value));

            case TypeCode.Int32:
                return(Runtime.PyInt_FromInt32((int)value));

            case TypeCode.Boolean:
                if ((bool)value)
                {
                    Runtime.XIncref(Runtime.PyTrue);
                    return(Runtime.PyTrue);
                }
                Runtime.XIncref(Runtime.PyFalse);
                return(Runtime.PyFalse);

            case TypeCode.Byte:
                return(Runtime.PyInt_FromInt32((int)((byte)value)));

            case TypeCode.Char:
                return(Runtime.PyUnicode_FromOrdinal((int)((char)value)));

            case TypeCode.Int16:
                return(Runtime.PyInt_FromInt32((int)((short)value)));

            case TypeCode.Int64:
                return(Runtime.PyLong_FromLongLong((long)value));

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string ss = ((float)value).ToString(nfi);
                IntPtr ps = Runtime.PyString_FromString(ss);
                IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
                Runtime.XDecref(ps);
                return(op);

            case TypeCode.Double:
                return(Runtime.PyFloat_FromDouble((double)value));

            case TypeCode.SByte:
                return(Runtime.PyInt_FromInt32((int)((sbyte)value)));

            case TypeCode.UInt16:
                return(Runtime.PyInt_FromInt32((int)((ushort)value)));

            case TypeCode.UInt32:
                return(Runtime.PyLong_FromUnsignedLong((uint)value));

            case TypeCode.UInt64:
                return(Runtime.PyLong_FromUnsignedLongLong((ulong)value));

            case TypeCode.Decimal:
                string d2s         = ((decimal)value).ToString(nfi);
                IntPtr d2p         = Runtime.PyString_FromString(d2s);
                IntPtr decimalArgs = Runtime.PyTuple_New(1);
                Runtime.PyTuple_SetItem(decimalArgs, 0, d2p);

                return(Runtime.PyObject_CallObject(decimalCtor, decimalArgs));

            case TypeCode.DateTime:
                var datetime = (DateTime)value;

                IntPtr dateTimeArgs = Runtime.PyTuple_New(8);
                Runtime.PyTuple_SetItem(dateTimeArgs, 0, Runtime.PyInt_FromInt32(datetime.Year));
                Runtime.PyTuple_SetItem(dateTimeArgs, 1, Runtime.PyInt_FromInt32(datetime.Month));
                Runtime.PyTuple_SetItem(dateTimeArgs, 2, Runtime.PyInt_FromInt32(datetime.Day));
                Runtime.PyTuple_SetItem(dateTimeArgs, 3, Runtime.PyInt_FromInt32(datetime.Hour));
                Runtime.PyTuple_SetItem(dateTimeArgs, 4, Runtime.PyInt_FromInt32(datetime.Minute));
                Runtime.PyTuple_SetItem(dateTimeArgs, 5, Runtime.PyInt_FromInt32(datetime.Second));
                Runtime.PyTuple_SetItem(dateTimeArgs, 6, Runtime.PyInt_FromInt32(1000 * datetime.Millisecond));
                Runtime.PyTuple_SetItem(dateTimeArgs, 7, TzInfo(datetime.Kind));

                return(Runtime.PyObject_CallObject(dateTimeCtor, dateTimeArgs));

            default:
                if (value is IEnumerable)
                {
                    using (var resultlist = new PyList())
                    {
                        foreach (object o in (IEnumerable)value)
                        {
                            using (var p = new PyObject(ToPython(o, o?.GetType())))
                            {
                                resultlist.Append(p);
                            }
                        }
                        Runtime.XIncref(resultlist.Handle);
                        return(resultlist.Handle);
                    }
                }
                result = CLRObject.GetInstHandle(value, type);
                return(result);
            }
        }
Ejemplo n.º 9
0
        internal static IntPtr ToPython(object value, Type type)
        {
            if (value is PyObject)
            {
                IntPtr handle = ((PyObject)value).Handle;
                Runtime.XIncref(handle);
                return(handle);
            }
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.XIncref(result);
                return(result);
            }

            if (Type.GetTypeCode(type) == TypeCode.Object && value.GetType() != typeof(object))
            {
                var encoded = PyObjectConversions.TryEncode(value, type);
                if (encoded != null)
                {
                    result = encoded.Handle;
                    Runtime.XIncref(result);
                    return(result);
                }
            }

            if (value is IList && !(value is INotifyPropertyChanged) && value.GetType().IsGenericType)
            {
                using (var resultlist = new PyList())
                {
                    foreach (object o in (IEnumerable)value)
                    {
                        using (var p = new PyObject(ToPython(o, o?.GetType())))
                        {
                            resultlist.Append(p);
                        }
                    }
                    Runtime.XIncref(resultlist.Handle);
                    return(resultlist.Handle);
                }
            }

            // it the type is a python subclass of a managed type then return the
            // underlying python object rather than construct a new wrapper object.
            var pyderived = value as IPythonDerivedType;

            if (null != pyderived)
            {
                if (!IsTransparentProxy(pyderived))
                {
                    return(ClassDerivedObject.ToPython(pyderived));
                }
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
            case TypeCode.Object:
                if (value is TimeSpan)
                {
                    var timespan = (TimeSpan)value;

                    IntPtr timeSpanArgs = Runtime.PyTuple_New(1);
                    Runtime.PyTuple_SetItem(timeSpanArgs, 0, Runtime.PyFloat_FromDouble(timespan.TotalDays));
                    var returnTimeSpan = Runtime.PyObject_CallObject(timeSpanCtor, timeSpanArgs);
                    // clean up
                    Runtime.XDecref(timeSpanArgs);
                    return(returnTimeSpan);
                }
                return(CLRObject.GetInstHandle(value, type));

            case TypeCode.String:
                return(Runtime.PyUnicode_FromString((string)value));

            case TypeCode.Int32:
                return(Runtime.PyInt_FromInt32((int)value));

            case TypeCode.Boolean:
                if ((bool)value)
                {
                    Runtime.XIncref(Runtime.PyTrue);
                    return(Runtime.PyTrue);
                }
                Runtime.XIncref(Runtime.PyFalse);
                return(Runtime.PyFalse);

            case TypeCode.Byte:
                return(Runtime.PyInt_FromInt32((int)((byte)value)));

            case TypeCode.Char:
                return(Runtime.PyUnicode_FromOrdinal((int)((char)value)));

            case TypeCode.Int16:
                return(Runtime.PyInt_FromInt32((int)((short)value)));

            case TypeCode.Int64:
                return(Runtime.PyLong_FromLongLong((long)value));

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string       ss = ((float)value).ToString(nfi);
                IntPtr       ps = Runtime.PyString_FromString(ss);
                NewReference op = Runtime.PyFloat_FromString(new BorrowedReference(ps));;
                Runtime.XDecref(ps);
                return(op.DangerousMoveToPointerOrNull());

            case TypeCode.Double:
                return(Runtime.PyFloat_FromDouble((double)value));

            case TypeCode.SByte:
                return(Runtime.PyInt_FromInt32((int)((sbyte)value)));

            case TypeCode.UInt16:
                return(Runtime.PyInt_FromInt32((int)((ushort)value)));

            case TypeCode.UInt32:
                return(Runtime.PyLong_FromUnsignedLong((uint)value));

            case TypeCode.UInt64:
                return(Runtime.PyLong_FromUnsignedLongLong((ulong)value));

            case TypeCode.Decimal:
                // C# decimal to python decimal has a big impact on performance
                // so we will use C# double and python float
                return(Runtime.PyFloat_FromDouble(decimal.ToDouble((decimal)value)));

            case TypeCode.DateTime:
                var datetime = (DateTime)value;

                var size = datetime.Kind == DateTimeKind.Unspecified ? 7 : 8;

                IntPtr dateTimeArgs = Runtime.PyTuple_New(size);
                Runtime.PyTuple_SetItem(dateTimeArgs, 0, Runtime.PyInt_FromInt32(datetime.Year));
                Runtime.PyTuple_SetItem(dateTimeArgs, 1, Runtime.PyInt_FromInt32(datetime.Month));
                Runtime.PyTuple_SetItem(dateTimeArgs, 2, Runtime.PyInt_FromInt32(datetime.Day));
                Runtime.PyTuple_SetItem(dateTimeArgs, 3, Runtime.PyInt_FromInt32(datetime.Hour));
                Runtime.PyTuple_SetItem(dateTimeArgs, 4, Runtime.PyInt_FromInt32(datetime.Minute));
                Runtime.PyTuple_SetItem(dateTimeArgs, 5, Runtime.PyInt_FromInt32(datetime.Second));

                // datetime.datetime 6th argument represents micro seconds
                var totalSeconds = datetime.TimeOfDay.TotalSeconds;
                var microSeconds = Convert.ToInt32((totalSeconds - Math.Truncate(totalSeconds)) * 1000000);
                if (microSeconds == 1000000)
                {
                    microSeconds = 999999;
                }
                Runtime.PyTuple_SetItem(dateTimeArgs, 6, Runtime.PyInt_FromInt32(microSeconds));

                if (size == 8)
                {
                    Runtime.PyTuple_SetItem(dateTimeArgs, 7, TzInfo(datetime.Kind));
                }

                var returnDateTime = Runtime.PyObject_CallObject(dateTimeCtor, dateTimeArgs);
                // clean up
                Runtime.XDecref(dateTimeArgs);
                return(returnDateTime);


            default:
                if (value is IEnumerable)
                {
                    using (var resultlist = new PyList())
                    {
                        foreach (object o in (IEnumerable)value)
                        {
                            using (var p = new PyObject(ToPython(o, o?.GetType())))
                            {
                                resultlist.Append(p);
                            }
                        }
                        Runtime.XIncref(resultlist.Handle);
                        return(resultlist.Handle);
                    }
                }
                result = CLRObject.GetInstHandle(value, type);
                return(result);
            }
        }