Python clr.GetClrType() Examples
The following are 30
code examples of clr.GetClrType().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
clr
, or try the search function
.
Example #1
Source File: clrtype.py From ironpython3 with Apache License 2.0 | 6 votes |
def validate_clr_types(signature_types, var_signature = False): if not isinstance(signature_types, tuple): signature_types = (signature_types,) for t in signature_types: if type(t) is type(System.IComparable): # type overloaded on generic arity, eg IComparable and IComparable[T] t = t[()] # select non-generic version clr_type = clr.GetClrType(t) if t == Void: raise TypeError("Void cannot be used in signature") is_typed = clr.GetPythonType(clr_type) == t # is_typed needs to be weakened until the generated type # gets explicitly published as the underlying CLR type is_typed = is_typed or (hasattr(t, "__metaclass__") and t.__metaclass__ in [ClrInterface, ClrClass]) if not is_typed: raise Exception("Invalid CLR type %s" % str(t)) if not var_signature: if clr_type.IsByRef: raise TypeError("Byref can only be used as arguments and locals") # ArgIterator is not present in Silverlight if hasattr(System, "ArgIterator") and t == System.ArgIterator: raise TypeError("Stack-referencing types can only be used as arguments and locals")
Example #2
Source File: test_missing.py From ironpython2 with Apache License 2.0 | 6 votes |
def CreateAssemblyGenerator(path, name): dir = IO.Path.GetDirectoryName(path) file = IO.Path.GetFileName(path) aname = Reflection.AssemblyName(name) domain = System.AppDomain.CurrentDomain ab = domain.DefineDynamicAssembly(aname, Emit.AssemblyBuilderAccess.RunAndSave, dir, None) mb = ab.DefineDynamicModule(file, file, True); ab.DefineVersionInfoResource() constructor = clr.GetClrType(Diagnostics.DebuggableAttribute).GetConstructor(MakeArray(System.Type, clr.GetClrType(Diagnostics.DebuggableAttribute.DebuggingModes))) attributeValue = MakeArray(System.Object, Diagnostics.DebuggableAttribute.DebuggingModes.Default | Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations | Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints ) cab = Emit.CustomAttributeBuilder(constructor, attributeValue) ab.SetCustomAttribute(cab) mb.SetCustomAttribute(cab) return AssemblyGenerator(file, ab, mb, None)
Example #3
Source File: clrtype.py From ironpython2 with Apache License 2.0 | 6 votes |
def add_wrapper_ctors(self, baseType, typebld): python_type_field = self.emit_python_type_field(typebld) for ctor in baseType.GetConstructors(): ctorparams = ctor.GetParameters() # leave out the PythonType argument assert(ctorparams[0].ParameterType == clr.GetClrType(PythonType)) ctorparams = ctorparams[1:] ctorbld = typebld.DefineConstructor( ctor.Attributes, ctor.CallingConvention, tuple([p.ParameterType for p in ctorparams])) ilgen = ctorbld.GetILGenerator() ilgen.Emit(OpCodes.Ldarg, 0) ilgen.Emit(OpCodes.Ldsfld, python_type_field) for index in xrange(len(ctorparams)): ilgen.Emit(OpCodes.Ldarg, index + 1) ilgen.Emit(OpCodes.Call, ctor) ilgen.Emit(OpCodes.Ret)
Example #4
Source File: clrtype.py From ironpython2 with Apache License 2.0 | 6 votes |
def validate_clr_types(signature_types, var_signature = False): if not isinstance(signature_types, tuple): signature_types = (signature_types,) for t in signature_types: if type(t) is type(System.IComparable): # type overloaded on generic arity, eg IComparable and IComparable[T] t = t[()] # select non-generic version clr_type = clr.GetClrType(t) if t == Void: raise TypeError("Void cannot be used in signature") is_typed = clr.GetPythonType(clr_type) == t # is_typed needs to be weakened until the generated type # gets explicitly published as the underlying CLR type is_typed = is_typed or (hasattr(t, "__metaclass__") and t.__metaclass__ in [ClrInterface, ClrClass]) if not is_typed: raise Exception, "Invalid CLR type %s" % str(t) if not var_signature: if clr_type.IsByRef: raise TypeError("Byref can only be used as arguments and locals") # ArgIterator is not present in Silverlight if hasattr(System, "ArgIterator") and t == System.ArgIterator: raise TypeError("Stack-referencing types can only be used as arguments and locals")
Example #5
Source File: clrtype.py From ironpython2 with Apache License 2.0 | 6 votes |
def make_cab(attrib_type, *args, **kwds): clrtype = clr.GetClrType(attrib_type) argtypes = tuple(map(lambda x:clr.GetClrType(type(x)), args)) ci = clrtype.GetConstructor(argtypes) props = ([],[]) fields = ([],[]) for kwd in kwds: pi = clrtype.GetProperty(kwd) if pi is not None: props[0].append(pi) props[1].append(kwds[kwd]) else: fi = clrtype.GetField(kwd) if fi is not None: fields[0].append(fi) fields[1].append(kwds[kwd]) else: raise TypeError("No %s Member found on %s" % (kwd, clrtype.Name)) return CustomAttributeBuilder(ci, args, tuple(props[0]), tuple(props[1]), tuple(fields[0]), tuple(fields[1]))
Example #6
Source File: clrtype.py From unity-python with MIT License | 6 votes |
def validate_clr_types(signature_types, var_signature = False): if not isinstance(signature_types, tuple): signature_types = (signature_types,) for t in signature_types: if type(t) is type(System.IComparable): # type overloaded on generic arity, eg IComparable and IComparable[T] t = t[()] # select non-generic version clr_type = clr.GetClrType(t) if t == Void: raise TypeError("Void cannot be used in signature") is_typed = clr.GetPythonType(clr_type) == t # is_typed needs to be weakened until the generated type # gets explicitly published as the underlying CLR type is_typed = is_typed or (hasattr(t, "__metaclass__") and t.__metaclass__ in [ClrInterface, ClrClass]) if not is_typed: raise Exception, "Invalid CLR type %s" % str(t) if not var_signature: if clr_type.IsByRef: raise TypeError("Byref can only be used as arguments and locals") # ArgIterator is not present in Silverlight if hasattr(System, "ArgIterator") and t == System.ArgIterator: raise TypeError("Stack-referencing types can only be used as arguments and locals")
Example #7
Source File: win32_pinvoke.py From RevitBatchProcessor with GNU General Public License v3.0 | 6 votes |
def GetWinApiFunctionImpl( functionName, moduleName, charSet, returnType, *parameterTypes ): tbuilder = MODULE_BUILDER.DefineType("WIN_API_TYPE" + "_" + moduleName + "_" + functionName) mbuilder = tbuilder.DefinePInvokeMethod( functionName, moduleName, PINVOKE_METHOD_ATTRIBUTES, Refl.CallingConventions.Standard, clr.GetClrType(returnType), [clr.GetClrType(t) for t in parameterTypes].ToArray[System.Type](), WIN_API_CALLING_CONVENTION, charSet ) mbuilder.SetImplementationFlags(mbuilder.MethodImplementationFlags | Refl.MethodImplAttributes.PreserveSig) winApiType = tbuilder.CreateType() methodInfo = winApiType.GetMethod(functionName, PUBLIC_STATIC_BINDING_FLAGS) def WinApiFunction(*parameters): return methodInfo.Invoke(None, parameters.ToArray[System.Object]()) return WinApiFunction
Example #8
Source File: test_reachtype.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_type_from_reflection_emit(self): import clr import System if is_netcoreapp: clr.AddReference("System.Reflection.Emit") sr = System.Reflection sre = System.Reflection.Emit array = System.Array cab = array[sre.CustomAttributeBuilder]([sre.CustomAttributeBuilder(clr.GetClrType(System.Security.SecurityTransparentAttribute).GetConstructor(System.Type.EmptyTypes), array[object]([]))]) if is_netcoreapp: # no System.AppDomain.DefineDynamicAssembly ab = sre.AssemblyBuilder.DefineDynamicAssembly(sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.Run, cab) # tracking: 291888 else: ab = System.AppDomain.CurrentDomain.DefineDynamicAssembly(sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.RunAndSave, "temp", None, None, None, None, True, cab) # tracking: 291888 mb = ab.DefineDynamicModule("temp", "temp.dll") tb = mb.DefineType("EmittedNS.EmittedType", sr.TypeAttributes.Public) tb.CreateType() clr.AddReference(ab) import EmittedNS EmittedNS.EmittedType()
Example #9
Source File: test_reachtype.py From ironpython3 with Apache License 2.0 | 6 votes |
def test_type_from_reflection_emit(self): import clr import System if is_netcoreapp: clr.AddReference("System.Reflection.Emit") sr = System.Reflection sre = System.Reflection.Emit array = System.Array cab = array[sre.CustomAttributeBuilder]([sre.CustomAttributeBuilder(clr.GetClrType(System.Security.SecurityTransparentAttribute).GetConstructor(System.Type.EmptyTypes), array[object]([]))]) if is_netcoreapp: # no System.AppDomain.DefineDynamicAssembly ab = sre.AssemblyBuilder.DefineDynamicAssembly(sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.Run, cab) # tracking: 291888 else: ab = System.AppDomain.CurrentDomain.DefineDynamicAssembly(sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.RunAndSave, "temp", None, None, None, None, True, cab) # tracking: 291888 mb = ab.DefineDynamicModule("temp", "temp.dll") tb = mb.DefineType("EmittedNS.EmittedType", sr.TypeAttributes.Public) tb.CreateType() clr.AddReference(ab) import EmittedNS EmittedNS.EmittedType()
Example #10
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_serializable_clionly(self): import clr import System from IronPythonTest import ExceptionsTest path = clr.GetClrType(ExceptionsTest).Assembly.Location mbro = System.AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(path, "IronPythonTest.EngineTest") self.assertRaises(AssertionError, mbro.Run, 'raise AssertionError') import exceptions for eh in dir(exceptions): eh = getattr(exceptions, eh) if isinstance(eh, type) and issubclass(eh, BaseException): # unicode exceptions require more args... if (eh.__name__ != 'UnicodeDecodeError' and eh.__name__ != 'UnicodeEncodeError' and eh.__name__ != 'UnicodeTranslateError'): self.assertRaises(eh, mbro.Run, 'raise ' + eh.__name__)
Example #11
Source File: test_missing.py From ironpython3 with Apache License 2.0 | 6 votes |
def CreateAssemblyGenerator(path, name): dir = IO.Path.GetDirectoryName(path) file = IO.Path.GetFileName(path) aname = Reflection.AssemblyName(name) domain = System.AppDomain.CurrentDomain ab = domain.DefineDynamicAssembly(aname, Emit.AssemblyBuilderAccess.RunAndSave, dir, None) mb = ab.DefineDynamicModule(file, file, True); ab.DefineVersionInfoResource() constructor = clr.GetClrType(Diagnostics.DebuggableAttribute).GetConstructor(MakeArray(System.Type, clr.GetClrType(Diagnostics.DebuggableAttribute.DebuggingModes))) attributeValue = MakeArray(System.Object, Diagnostics.DebuggableAttribute.DebuggingModes.Default | Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations | Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints ) cab = Emit.CustomAttributeBuilder(constructor, attributeValue) ab.SetCustomAttribute(cab) mb.SetCustomAttribute(cab) return AssemblyGenerator(file, ab, mb, None)
Example #12
Source File: clrtype.py From ironpython3 with Apache License 2.0 | 6 votes |
def make_cab(attrib_type, *args, **kwds): clrtype = clr.GetClrType(attrib_type) argtypes = tuple(map(lambda x:clr.GetClrType(type(x)), args)) ci = clrtype.GetConstructor(argtypes) props = ([],[]) fields = ([],[]) for kwd in kwds: pi = clrtype.GetProperty(kwd) if pi is not None: props[0].append(pi) props[1].append(kwds[kwd]) else: fi = clrtype.GetField(kwd) if fi is not None: fields[0].append(fi) fields[1].append(kwds[kwd]) else: raise TypeError("No %s Member found on %s" % (kwd, clrtype.Name)) return CustomAttributeBuilder(ci, args, tuple(props[0]), tuple(props[1]), tuple(fields[0]), tuple(fields[1]))
Example #13
Source File: clrtype.py From unity-python with MIT License | 6 votes |
def make_cab(attrib_type, *args, **kwds): clrtype = clr.GetClrType(attrib_type) argtypes = tuple(map(lambda x:clr.GetClrType(type(x)), args)) ci = clrtype.GetConstructor(argtypes) props = ([],[]) fields = ([],[]) for kwd in kwds: pi = clrtype.GetProperty(kwd) if pi is not None: props[0].append(pi) props[1].append(kwds[kwd]) else: fi = clrtype.GetField(kwd) if fi is not None: fields[0].append(fi) fields[1].append(kwds[kwd]) else: raise TypeError("No %s Member found on %s" % (kwd, clrtype.Name)) return CustomAttributeBuilder(ci, args, tuple(props[0]), tuple(props[1]), tuple(fields[0]), tuple(fields[1]))
Example #14
Source File: test_clrtype.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_interface_members(self): # Calling IProduct.Name and IProduct.IsAvailable as a strongly-typed members name = clr.GetClrType(IProduct).GetProperty("Name").GetGetMethod() self.assertEqual(name.Invoke(self.p, None), 'Widget') isAvailable = clr.GetClrType(IProduct).GetMethod("IsAvailable") self.assertTrue(isAvailable.Invoke(self.p, None))
Example #15
Source File: test_cliclass.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_nullable_new(self): from System import Nullable self.assertEqual(clr.GetClrType(Nullable[()]).IsGenericType, False)
Example #16
Source File: __init__.py From robotframework-whitelibrary with Apache License 2.0 | 5 votes |
def _get_item_by_partial_text(self, partial_text, item_type=None): items = self._get_multiple_items_by_partial_text(partial_text) try: if item_type is None: return next(items) return next((item for item in items if item.GetType() == clr.GetClrType(item_type))) except StopIteration: raise ItemNotFoundError(u"Item with partial text '{}' was not found".format(partial_text))
Example #17
Source File: exception_util.py From RevitBatchProcessor with GNU General Public License v3.0 | 5 votes |
def LogOutputErrorDetails(exception, output_, verbose=True): output = global_test_mode.PrefixedOutputForGlobalTestMode(output_, EXCEPTION_MESSAGE_HANDLER_PREFIX) exceptionMessage = ( str(exception.message) if isinstance(exception, exceptions.Exception) else str(exception.Message) if isinstance(exception, System.Exception) else str.Empty ) output() output("Exception: [" + type(exception).__name__ + "] " + exceptionMessage) try: clsException = GetClrException(exception) if clsException is not None: clsExceptionType = clr.GetClrType(type(clsException)) output(".NET exception: [" + str(clsExceptionType.Name) + "] " + str(clsException.Message)) if verbose: interpretedFrameInfo = GetInterpretedFrameInfo(clsException.Data) if interpretedFrameInfo is not None: output() output("Further exception information:") output() for i in interpretedFrameInfo: if str(i) != "CallSite.Target": output("\t" + str(i)) except: output("Could not obtain further exception information.") return
Example #18
Source File: revit_file_version.py From RevitBatchProcessor with GNU General Public License v3.0 | 5 votes |
def GetWindowsBaseAssembly(): return clr.GetClrType(Packaging.StorageInfo).Assembly
Example #19
Source File: clrtype.py From unity-python with MIT License | 5 votes |
def get_typed_properties(self): for item_name, item in self.__dict__.items(): if isinstance(item, property): if item.fget: if not self.is_typed_method(item.fget): continue prop_type = item.fget.return_type else: if not self.is_typed_method(item.fset): continue prop_type = item.fset.arg_types[0] validate_clr_types(prop_type) clr_prop_type = clr.GetClrType(prop_type) yield item, item_name, clr_prop_type
Example #20
Source File: test_exceptions.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_serializable_clionly(self): import clr import System from IronPythonTest import ExceptionsTest path = clr.GetClrType(ExceptionsTest).Assembly.Location mbro = System.AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(path, "IronPythonTest.EngineTest") self.assertRaises(AssertionError, mbro.Run, 'raise AssertionError') import builtins special_types = [UnicodeTranslateError, UnicodeEncodeError, UnicodeDecodeError] # unicode exceptions require more args... exception_types = [x for x in builtins.__dict__.values() if isinstance(x, type) and issubclass(x, BaseException) and x not in special_types] for eh in exception_types: self.assertRaises(eh, mbro.Run, 'raise ' + eh.__name__)
Example #21
Source File: test_ipye.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_engine_access_from_within(): import clr from Microsoft.Scripting.Hosting import ScriptEngine pc = clr.GetCurrentRuntime().GetLanguageByName('python') engine = pc.GetModuleState(clr.GetClrType(ScriptEngine)) Assert(engine is not None)
Example #22
Source File: clrtype.py From unity-python with MIT License | 5 votes |
def emit_fields(self, typebld): if hasattr(self, "_clrfields"): for fldname in self._clrfields: field_type = self._clrfields[fldname] validate_clr_types(field_type) typebld.DefineField( fldname, clr.GetClrType(field_type), FieldAttributes.Public)
Example #23
Source File: test_missing.py From ironpython3 with Apache License 2.0 | 5 votes |
def MakeArray(type, *values): a = System.Array.CreateInstance(clr.GetClrType(type), len(values)) for i in range(len(values)): a[i] = values[i] return a
Example #24
Source File: generate_comdispatch.py From ironpython3 with Apache License 2.0 | 5 votes |
def gen_ManagedToComPrimitiveTypes(cw): import System import clr # build inverse map type_map = {} for variantType in variantTypes: # take them in order, first one wins ... handles ERROR and INT32 conflict if variantType.isPrimitiveType and variantType.managedType not in type_map: type_map[variantType.managedType] = variantType.variantType for managedType, variantType in managed_types_to_variant_types_add: type_map[managedType] = variantType def is_system_type(name): t = getattr(System, name, None) return t and System.Type.GetTypeCode(t) not in [System.TypeCode.Empty, System.TypeCode.Object] system_types = filter(is_system_type, type_map.keys()) system_types = sorted(system_types, key=lambda name: int(System.Type.GetTypeCode(getattr(System, name)))) other_types = sorted(set(type_map.keys()).difference(set(system_types))) # switch from sytem types cw.enter_block("switch (Type.GetTypeCode(argumentType))") for t in system_types: cw.write("""case TypeCode.%(code)s: primitiveVarEnum = VarEnum.VT_%(vt)s; return true;""", code = System.Type.GetTypeCode(getattr(System, t)).ToString(), vt = type_map[t]) cw.exit_block() # if statements from the rest for t in other_types: clrtype = getattr(System, t, None) if not clrtype: clrtype = getattr(System.Runtime.InteropServices, t, None) clrtype = clr.GetClrType(clrtype) cw.write(""" if (argumentType == typeof(%(type)s)) { primitiveVarEnum = VarEnum.VT_%(vt)s; return true; }""", type = clrtype.Name, vt = type_map[t])
Example #25
Source File: generate_alltypes.py From ironpython3 with Apache License 2.0 | 5 votes |
def __init__(self, type): self.name = clr.GetClrType(type).Name self.type = type self.ops = self.name+"Ops" self.min, self.max = get_min_max(type) self.is_signed = self.min < 0 self.size = self.max-self.min + 1 try: self.is_float = self.type(1) // self.type(2) != self.type(0.5) except: self.is_float = True
Example #26
Source File: clrtype.py From ironpython3 with Apache License 2.0 | 5 votes |
def emit_fields(self, typebld): if hasattr(self, "_clrfields"): for fldname in self._clrfields: field_type = self._clrfields[fldname] validate_clr_types(field_type) typebld.DefineField( fldname, clr.GetClrType(field_type), FieldAttributes.Public)
Example #27
Source File: clrtype.py From ironpython3 with Apache License 2.0 | 5 votes |
def map_clr_type(self, clr_type): """ TODO - Currently "t = clr.GetPythonType(clr.GetClrType(C)); t == C" will be False for C where C.__metaclass__ is ClrInterface, even though both t and C represent the same CLR type. This can be fixed by publishing a mapping between t and C in the IronPython runtime. """ pass
Example #28
Source File: clrtype.py From ironpython3 with Apache License 2.0 | 5 votes |
def get_typed_properties(self): for item_name, item in self.__dict__.items(): if isinstance(item, property): if item.fget: if not self.is_typed_method(item.fget): continue prop_type = item.fget.return_type else: if not self.is_typed_method(item.fset): continue prop_type = item.fset.arg_types[0] validate_clr_types(prop_type) clr_prop_type = clr.GetClrType(prop_type) yield item, item_name, clr_prop_type
Example #29
Source File: clrtype.py From ironpython3 with Apache License 2.0 | 5 votes |
def emit_classattribs(self, typebld): if hasattr(self, '_clrclassattribs'): for attrib_info in self._clrclassattribs: if isinstance(attrib_info, type): ci = clr.GetClrType(attrib_info).GetConstructor(()) cab = CustomAttributeBuilder(ci, ()) elif isinstance(attrib_info, CustomAttributeDecorator): cab = attrib_info.GetBuilder() else: make_decorator = attrib_info() cab = make_decorator.GetBuilder() typebld.SetCustomAttribute(cab)
Example #30
Source File: clrtype.py From unity-python with MIT License | 5 votes |
def map_clr_type(self, clr_type): """ TODO - Currently "t = clr.GetPythonType(clr.GetClrType(C)); t == C" will be False for C where C.__metaclass__ is ClrInterface, even though both t and C represent the same CLR type. This can be fixed by publishing a mapping between t and C in the IronPython runtime. """ pass