/// <summary> /// PyDict Constructor /// </summary> /// <remarks> /// Creates a new Python dictionary object. /// </remarks> public PyDict() : base(Runtime.PyDict_New()) { if (obj == IntPtr.Zero) { throw new PythonException(); } }
internal CLRObject(object ob, IntPtr tp) { IntPtr py = Runtime.PyType_GenericAlloc(tp, 0); long flags = Util.ReadCLong(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Subclass) != 0) { IntPtr dict = Marshal.ReadIntPtr(py, ObjectOffset.TypeDictOffset(tp)); if (dict == IntPtr.Zero) { dict = Runtime.PyDict_New(); Marshal.WriteIntPtr(py, ObjectOffset.TypeDictOffset(tp), dict); } } GCHandle gc = GCHandle.Alloc(this); Marshal.WriteIntPtr(py, ObjectOffset.magic(tp), (IntPtr)gc); tpHandle = tp; pyHandle = py; gcHandle = gc; inst = ob; // for performance before calling SetArgsAndCause() lets check if we are an exception if (inst is Exception) { // Fix the BaseException args (and __cause__ in case of Python 3) // slot if wrapping a CLR exception Exceptions.SetArgsAndCause(py); } }
internal CLRObject(object ob, IntPtr tp) { System.Diagnostics.Debug.Assert(tp != IntPtr.Zero); IntPtr py = Runtime.PyType_GenericAlloc(tp, 0); long flags = Util.ReadCLong(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Subclass) != 0) { IntPtr dict = Marshal.ReadIntPtr(py, ObjectOffset.TypeDictOffset(tp)); if (dict == IntPtr.Zero) { dict = Runtime.PyDict_New(); Marshal.WriteIntPtr(py, ObjectOffset.TypeDictOffset(tp), dict); } } GCHandle gc = AllocGCHandle(TrackTypes.Wrapper); Marshal.WriteIntPtr(py, ObjectOffset.magic(tp), (IntPtr)gc); tpHandle = tp; pyHandle = py; inst = ob; // Fix the BaseException args (and __cause__ in case of Python 3) // slot if wrapping a CLR exception Exceptions.SetArgsAndCause(py); }
internal CLRObject(Object ob, IntPtr tp) : base() { IntPtr py = Runtime.PyType_GenericAlloc(tp, 0); int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Subclass) != 0) { IntPtr dict = Marshal.ReadIntPtr(py, ObjectOffset.ob_dict); if (dict == IntPtr.Zero) { dict = Runtime.PyDict_New(); Marshal.WriteIntPtr(py, ObjectOffset.ob_dict, dict); } } GCHandle gc = GCHandle.Alloc(this); Marshal.WriteIntPtr(py, ObjectOffset.magic(), (IntPtr)gc); this.tpHandle = tp; this.pyHandle = py; this.gcHandle = gc; inst = ob; //DebugUtil.DumpInst(py); }
internal CLRObject(Object ob, IntPtr tp) : base() { IntPtr py = Runtime.PyType_GenericAlloc(tp, 0); int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Subclass) != 0) { IntPtr dict = Marshal.ReadIntPtr(py, ObjectOffset.DictOffset(tp)); if (dict == IntPtr.Zero) { dict = Runtime.PyDict_New(); Marshal.WriteIntPtr(py, ObjectOffset.DictOffset(tp), dict); } } GCHandle gc = GCHandle.Alloc(this); Marshal.WriteIntPtr(py, ObjectOffset.magic(tp), (IntPtr)gc); this.tpHandle = tp; this.pyHandle = py; this.gcHandle = gc; inst = ob; // Fix the BaseException args (and __cause__ in case of Python 3) // slot if wrapping a CLR exception Exceptions.SetArgsAndCause(py); }
public static IntPtr CreateObjectType() { IntPtr globals = Runtime.PyDict_New(); if (Runtime.PyDict_SetItemString(globals, "__builtins__", Runtime.PyEval_GetBuiltins()) != 0) { Runtime.XDecref(globals); throw new PythonException(); } const string code = "class A(object): pass"; var resRef = Runtime.PyRun_String(code, RunFlagType.File, globals, globals); IntPtr res = resRef.DangerousGetAddress(); if (res == IntPtr.Zero) { try { throw new PythonException(); } finally { Runtime.XDecref(globals); } } resRef.Dispose(); IntPtr A = Runtime.PyDict_GetItemString(globals, "A"); Debug.Assert(A != IntPtr.Zero); Runtime.XIncref(A); Runtime.XDecref(globals); return(A); }
public ModuleObject(string name) : base() { moduleName = (name == String.Empty) ? "CLR" : name; cache = new Hashtable(); _namespace = name; dict = Runtime.PyDict_New(); IntPtr pyname = Runtime.PyString_FromString(moduleName); Runtime.PyDict_SetItemString(dict, "__name__", pyname); Runtime.PyDict_SetItemString(dict, "__file__", Runtime.PyNone); Runtime.PyDict_SetItemString(dict, "__doc__", Runtime.PyNone); Runtime.Decref(pyname); Marshal.WriteIntPtr(this.pyHandle, ObjectOffset.ob_dict, dict); // This hackery is required in order to allow a plain Python to // import the managed runtime via the CLR bootstrapper module. // The standard Python machinery in control at the time of the // import requires the module to pass PyModule_Check. :( if (!hacked) { IntPtr type = this.tpHandle; IntPtr mro = Marshal.ReadIntPtr(type, TypeOffset.tp_mro); IntPtr ext = Runtime.ExtendTuple(mro, Runtime.PyModuleType); Marshal.WriteIntPtr(type, TypeOffset.tp_mro, ext); Runtime.Decref(mro); hacked = true; } }
internal static void SetupExceptionHack() { ns_exc = ClassManager.GetClass(typeof(Exception)).pyHandle; cache = new Hashtable(); string code = "import exceptions\n" + "class Exception(exceptions.Exception):\n" + " _class = None\n" + " _inner = None\n" + "\n" + " def __init__(self, *args, **kw):\n" + " inst = self.__class__._class(*args, **kw)\n" + " self.__dict__['_inner'] = inst\n" + " exceptions.Exception.__init__(self, *args, **kw)\n" + "\n" + " def __getattr__(self, name, _marker=[]):\n" + " inner = self.__dict__['_inner']\n" + " v = getattr(inner, name, _marker)\n" + " if v is not _marker:\n" + " return v\n" + " v = self.__dict__.get(name, _marker)\n" + " if v is not _marker:\n" + " return v\n" + " raise AttributeError(name)\n" + "\n" + " def __setattr__(self, name, value):\n" + " inner = self.__dict__['_inner']\n" + " setattr(inner, name, value)\n" + "\n" + " def __str__(self):\n" + " inner = self.__dict__.get('_inner')\n" + " msg = getattr(inner, 'Message', '')\n" + " st = getattr(inner, 'StackTrace', '')\n" + " st = st and '\\n' + st or ''\n" + " return msg + st\n" + "\n"; IntPtr dict = Runtime.PyDict_New(); IntPtr builtins = Runtime.PyEval_GetBuiltins(); Runtime.PyDict_SetItemString(dict, "__builtins__", builtins); IntPtr namestr = Runtime.PyString_FromString("System"); Runtime.PyDict_SetItemString(dict, "__name__", namestr); Runtime.Decref(namestr); Runtime.PyDict_SetItemString(dict, "__file__", Runtime.PyNone); Runtime.PyDict_SetItemString(dict, "__doc__", Runtime.PyNone); IntPtr flag = Runtime.Py_file_input; IntPtr done = Runtime.PyRun_String(code, flag, dict, dict); os_exc = Runtime.PyDict_GetItemString(dict, "Exception"); Runtime.PyObject_SetAttrString(os_exc, "_class", ns_exc); Runtime.PyErr_Clear(); }
/// <summary> /// PyDict Constructor /// </summary> /// <remarks> /// Creates a new Python dictionary object. /// </remarks> public PyDict() { obj = Runtime.PyDict_New(); if (obj == IntPtr.Zero) { throw new PythonException(); } }
/// <summary> /// RunString Method /// </summary> /// <remarks> /// Run a string containing Python code. Returns the result of /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// </remarks> public static PyObject RunString( string code, IntPtr?globals = null, IntPtr?locals = null ) { var borrowedGlobals = true; if (globals == null) { globals = Runtime.PyEval_GetGlobals(); if (globals == IntPtr.Zero) { globals = Runtime.PyDict_New(); Runtime.PyDict_SetItemString( globals.Value, "__builtins__", Runtime.PyEval_GetBuiltins() ); borrowedGlobals = false; } } var borrowedLocals = true; if (locals == null) { locals = Runtime.PyDict_New(); borrowedLocals = false; } var flag = (IntPtr)257; /* Py_file_input */ try { IntPtr result = Runtime.PyRun_String( code, flag, globals.Value, locals.Value ); Py.Throw(); return(new PyObject(result)); } finally { if (!borrowedLocals) { Runtime.XDecref(locals.Value); } if (!borrowedGlobals) { Runtime.XDecref(globals.Value); } } }
/// <summary> /// Internal RunString Method. /// </summary> /// <remarks> /// Run a string containing Python code. Returns the result of /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// </remarks> internal static PyObject RunString(string code, IntPtr?globals, IntPtr?locals, RunFlagType flag) { var borrowedGlobals = true; if (globals == null) { globals = Runtime.PyEval_GetGlobals(); if (globals == IntPtr.Zero) { globals = Runtime.PyDict_New(); Runtime.PyDict_SetItemString( globals.Value, "__builtins__", Runtime.PyEval_GetBuiltins() ); borrowedGlobals = false; } } if (locals == null) { locals = globals; } try { NewReference result = Runtime.PyRun_String( code, (IntPtr)flag, globals.Value, locals.Value ); try { Runtime.CheckExceptionOccurred(); return(result.MoveToPyObject()); } finally { result.Dispose(); } } finally { if (!borrowedGlobals) { Runtime.XDecref(globals.Value); } } }
/// <summary> /// RunString Method /// </summary> /// /// <remarks> /// Run a string containing Python code. Returns the result of /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// </remarks> public static PyObject RunString(string code) { IntPtr globals = Runtime.PyEval_GetGlobals(); IntPtr locals = Runtime.PyDict_New(); IntPtr builtins = Runtime.PyEval_GetBuiltins(); Runtime.PyDict_SetItemString(locals, "__builtins__", builtins); IntPtr flag = (IntPtr)257; /* Py_file_input */ IntPtr result = Runtime.PyRun_String(code, flag, globals, locals); Runtime.Decref(locals); if (result == IntPtr.Zero) { return(null); } return(new PyObject(result)); }
public ModuleObject(string name) { if (name == string.Empty) { throw new ArgumentException("Name must not be empty!"); } moduleName = name; cache = new Dictionary <string, ManagedType>(); _namespace = name; // Use the filename from any of the assemblies just so there's something for // anything that expects __file__ to be set. var filename = "unknown"; var docstring = "Namespace containing types from the following assemblies:\n\n"; foreach (Assembly a in AssemblyManager.GetAssemblies(name)) { if (!a.IsDynamic && a.Location != null) { filename = a.Location; } docstring += "- " + a.FullName + "\n"; } dict = Runtime.PyDict_New(); IntPtr pyname = Runtime.PyString_FromString(moduleName); IntPtr pyfilename = Runtime.PyString_FromString(filename); IntPtr pydocstring = Runtime.PyString_FromString(docstring); IntPtr pycls = TypeManager.GetTypeHandle(GetType()); Runtime.PyDict_SetItem(dict, PyIdentifier.__name__, pyname); Runtime.PyDict_SetItem(dict, PyIdentifier.__file__, pyfilename); Runtime.PyDict_SetItem(dict, PyIdentifier.__doc__, pydocstring); Runtime.PyDict_SetItem(dict, PyIdentifier.__class__, pycls); Runtime.XDecref(pyname); Runtime.XDecref(pyfilename); Runtime.XDecref(pydocstring); Runtime.XIncref(dict); SetObjectDict(pyHandle, dict); InitializeModuleMembers(); }
public static IntPtr CreateObjectType() { using var globals = NewReference.DangerousFromPointer(Runtime.PyDict_New()); if (Runtime.PyDict_SetItemString(globals, "__builtins__", Runtime.PyEval_GetBuiltins()) != 0) { globals.Dispose(); throw new PythonException(); } const string code = "class A(object): pass"; using var resRef = Runtime.PyRun_String(code, RunFlagType.File, globals, globals); if (resRef.IsNull()) { globals.Dispose(); throw new PythonException(); } resRef.Dispose(); BorrowedReference A = Runtime.PyDict_GetItemString(globals, "A"); Debug.Assert(!A.IsNull); return(new NewReference(A).DangerousMoveToPointer()); }
internal static IntPtr GenerateExceptionClass(IntPtr real) { if (real == ns_exc) { return(os_exc); } IntPtr nbases = Runtime.PyObject_GetAttrString(real, "__bases__"); if (Runtime.PyTuple_Size(nbases) != 1) { throw new SystemException("Invalid __bases__"); } IntPtr nsbase = Runtime.PyTuple_GetItem(nbases, 0); Runtime.Decref(nbases); IntPtr osbase = GetExceptionClassWrapper(nsbase); IntPtr baselist = Runtime.PyTuple_New(1); Runtime.Incref(osbase); Runtime.PyTuple_SetItem(baselist, 0, osbase); IntPtr name = Runtime.PyObject_GetAttrString(real, "__name__"); IntPtr dict = Runtime.PyDict_New(); IntPtr mod = Runtime.PyObject_GetAttrString(real, "__module__"); Runtime.PyDict_SetItemString(dict, "__module__", mod); Runtime.Decref(mod); IntPtr subc = Runtime.PyClass_New(baselist, dict, name); Runtime.Decref(baselist); Runtime.Decref(dict); Runtime.Decref(name); Runtime.PyObject_SetAttrString(subc, "_class", real); return(subc); }
public ModuleObject(string name) : base() { if (name == String.Empty) { throw new ArgumentException("Name must not be empty!"); } moduleName = name; cache = new Dictionary <string, ManagedType>(); _namespace = name; dict = Runtime.PyDict_New(); IntPtr pyname = Runtime.PyString_FromString(moduleName); Runtime.PyDict_SetItemString(dict, "__name__", pyname); Runtime.PyDict_SetItemString(dict, "__file__", Runtime.PyNone); Runtime.PyDict_SetItemString(dict, "__doc__", Runtime.PyNone); Runtime.Decref(pyname); Marshal.WriteIntPtr(this.pyHandle, ObjectOffset.ob_dict, dict); InitializeModuleMembers(); }
public ModuleObject(string name) : base() { if (name == String.Empty) { throw new ArgumentException("Name must not be empty!"); } moduleName = name; cache = new Dictionary <string, ManagedType>(); _namespace = name; // Use the filename from any of the assemblies just so there's something for // anything that expects __file__ to be set. string filename = "unknown"; string docstring = "Namespace containing types from the following assemblies:\n\n"; foreach (Assembly a in AssemblyManager.GetAssemblies(name)) { filename = a.Location; docstring += "- " + a.FullName + "\n"; } dict = Runtime.PyDict_New(); IntPtr pyname = Runtime.PyString_FromString(moduleName); IntPtr pyfilename = Runtime.PyString_FromString(filename); IntPtr pydocstring = Runtime.PyString_FromString(docstring); IntPtr pycls = TypeManager.GetTypeHandle(this.GetType()); Runtime.PyDict_SetItemString(dict, "__name__", pyname); Runtime.PyDict_SetItemString(dict, "__file__", pyfilename); Runtime.PyDict_SetItemString(dict, "__doc__", pydocstring); Runtime.PyDict_SetItemString(dict, "__class__", pycls); Runtime.Decref(pyname); Runtime.Decref(pyfilename); Runtime.Decref(pydocstring); Marshal.WriteIntPtr(this.pyHandle, ObjectOffset.DictOffset(this.pyHandle), dict); InitializeModuleMembers(); }