Python System.Type() Examples

The following are 29 code examples of System.Type(). 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 System , or try the search function .
Example #1
Source File: test_missing.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: win32_pinvoke.py    From RevitBatchProcessor with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_close(self, sender, args):
            def _shutdown():
                if is_cef:
                    CEF.shutdown()
                WinForms.Application.Exit()

            if is_cef:
                CEF.close_window(self.uid)

            del BrowserView.instances[self.uid]

            # during tests windows is empty for some reason. no idea why.
            if self.pywebview_window in windows:
                windows.remove(self.pywebview_window)

            self.closed.set()

            if len(BrowserView.instances) == 0:
                self.Invoke(Func[Type](_shutdown)) 
Example #4
Source File: test_method_override.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_methods_from_generic_class(self):
        import System
        from Merlin.Testing.BaseClass import Class320
        class C(Class320[int]): pass
        x = C()
        self.assertEqual(x.m320(1), 11)
        self.assertRaises(TypeError, x.m320, 'abc')

        self.assertEqual(C.m320(x, 1), 11)
        self.assertEqual(Class320[int].m320(x, 1), 11)
        
        C.m320 = lambda self, arg: 100
        self.assertEqual(x.m320(1), 100)
        self.assertEqual(C.m320(x, 1), 100)
        self.assertEqual(Class320[int].m320(x, 1), 11)

        # ref type
        class C(Class320[System.Type]): pass
        x = C()
        self.assertRaises(TypeError, x.m320, 1)
        self.assertEqual(x.m320(None), 11)
        
        C.m320 = lambda self: 200
        self.assertEqual(x.m320(), 200) 
Example #5
Source File: test_missing.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: test___clrtype__.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_neg_clrtype_returns_nonsense_values(self):
        '''
        The __clrtype__ implementation returns invalid values.
        '''
        global called
        import System
        
        for x, expected_msg in [[[], "expected Type, got list"], 
                                [(None,), "expected Type, got tuple"], 
                                [True, "expected Type, got bool"], 
                                [False, "expected Type, got bool"], 
                                [3.14, "expected Type, got float"], 
                                ["a string", "expected Type, got str"],
                                [System.UInt16(32), "expected Type, got UInt16"],
                                [1L, "expected Type, got long"],
                    ]: 
Example #7
Source File: test_method_override.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_methods_from_generic_class(self):
        import System
        from Merlin.Testing.BaseClass import Class320
        class C(Class320[int]): pass
        x = C()
        self.assertEqual(x.m320(1), 11)
        self.assertRaises(TypeError, x.m320, 'abc')

        self.assertEqual(C.m320(x, 1), 11)
        self.assertEqual(Class320[int].m320(x, 1), 11)
        
        C.m320 = lambda self, arg: 100
        self.assertEqual(x.m320(1), 100)
        self.assertEqual(C.m320(x, 1), 100)
        self.assertEqual(Class320[int].m320(x, 1), 11)

        # ref type
        class C(Class320[System.Type]): pass
        x = C()
        self.assertRaises(TypeError, x.m320, 1)
        self.assertEqual(x.m320(None), 11)
        
        C.m320 = lambda self: 200
        self.assertEqual(x.m320(), 200) 
Example #8
Source File: test_missing.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def DefineMethod(self, name, attributes, returnType, parameterTypes):
        params = MakeArray(System.Type, parameterTypes)
        mb = self.tb.DefineMethod(name, attributes, returnType, params)
        ilg = mb.GetILGenerator()
        return CodeGenerator(self, mb, ilg) 
Example #9
Source File: load_library.py    From msl-loadlib with MIT License 5 votes vote down vote up
def __init__(self, dot_net_dict, path):
        """Contains the namespace_ modules, classes and `System.Type`_ objects of a .NET Assembly.

        Do not instantiate this class directly.

        .. _namespace: https://msdn.microsoft.com/en-us/library/z2kcy19k.aspx
        .. _System.Type: https://msdn.microsoft.com/en-us/library/system.type(v=vs.110).aspx
        """
        self.__dict__.update(dot_net_dict)
        self._path = path 
Example #10
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def destroy_window(uid):
    def _close():
        window.Close()

    window = BrowserView.instances[uid]
    window.Invoke(Func[Type](_close))

    if not is_cef:
        window.browser.js_result_semaphore.release() 
Example #11
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_window(window):
    def create():
        browser = BrowserView.BrowserForm(window)
        BrowserView.instances[window.uid] = browser

        if not window.hidden:
            browser.Show()

        _main_window_created.set()

        if window.uid == 'master':
            app.Run()

    app = WinForms.Application

    if window.uid == 'master':
        if not is_edge and not is_cef:
            _set_ie_mode()

        if sys.getwindowsversion().major >= 6:
            windll.user32.SetProcessDPIAware()

        if is_cef:
            CEF.init(window)

        app.EnableVisualStyles()
        app.SetCompatibleTextRenderingDefault(False)
        thread = Thread(ThreadStart(create))
        thread.SetApartmentState(ApartmentState.STA)
        thread.Start()
        thread.Join()

    else:
        _main_window_created.wait()
        i = list(BrowserView.instances.values())[0]     # arbitrary instance
        i.Invoke(Func[Type](create)) 
Example #12
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def restore(self):
            def _restore():
                self.WindowState = WinForms.FormWindowState.Normal

            self.Invoke(Func[Type](_restore)) 
Example #13
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def minimize(self):
            def _minimize():
                self.WindowState = WinForms.FormWindowState.Minimized

            self.Invoke(Func[Type](_minimize)) 
Example #14
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_top(self, on_top):
            def _set():
                z_order = -1 if on_top is True else -2
                SWP_NOSIZE = 0x0001  # Retains the current size
                windll.user32.SetWindowPos(self.Handle.ToInt32(), z_order, self.Location.X, self.Location.Y, None, None, SWP_NOSIZE)
            if self.InvokeRequired:
                self.Invoke(Func[Type](_set))
            else:
                _set() 
Example #15
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def toggle_fullscreen(self):
            def _toggle():
                screen = WinForms.Screen.FromControl(self)

                if not self.is_fullscreen:
                    self.old_size = self.Size
                    self.old_state = self.WindowState
                    self.old_style = self.FormBorderStyle
                    self.old_location = self.Location
                    self.FormBorderStyle = 0  # FormBorderStyle.None
                    self.Bounds = WinForms.Screen.PrimaryScreen.Bounds
                    self.WindowState = WinForms.FormWindowState.Maximized
                    self.is_fullscreen = True
                    windll.user32.SetWindowPos(self.Handle.ToInt32(), None, screen.Bounds.X, screen.Bounds.Y,
                                            screen.Bounds.Width, screen.Bounds.Height, 64)
                else:
                    self.Size = self.old_size
                    self.WindowState = self.old_state
                    self.FormBorderStyle = self.old_style
                    self.Location = self.old_location
                    self.is_fullscreen = False

            if self.InvokeRequired:
                self.Invoke(Func[Type](_toggle))
            else:
                _toggle() 
Example #16
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hide(self):
            self.Invoke(Func[Type](self.Hide)) 
Example #17
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_url(self, url):
            def _load_url():
                self.browser.load_url(url)

            self.Invoke(Func[Type](_load_url)) 
Example #18
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_html(self, content, base_uri):
            def _load_html():
                 self.browser.load_html(content, base_uri)

            self.Invoke(Func[Type](_load_html)) 
Example #19
Source File: winforms.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def evaluate_js(self, script):
            def _evaluate_js():
                self.browser.evaluate_js(script)

            self.loaded.wait()
            self.Invoke(Func[Type](_evaluate_js))
            self.browser.js_result_semaphore.acquire()

            return self.browser.js_result 
Example #20
Source File: test_missing.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def DefineMethod(self, name, attributes, returnType, parameterTypes):
        params = MakeArray(System.Type, parameterTypes)
        mb = self.tb.DefineMethod(name, attributes, returnType, params)
        ilg = mb.GetILGenerator()
        return CodeGenerator(self, mb, ilg) 
Example #21
Source File: test___clrtype__.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def test_clrtype_returns_existing_python_types(self):
        '''
        Our implementation of __clrtype__ returns pure-Python types
        instead of subclassing from type or System.Type and implementing
        __clrtype__.
        '''
        global called
        
        class PySubType1(type): pass
        class PySubType2(PySubType1): pass
        class PySubType3(PySubType2, PySubType1): pass
        
        for x in [
                    bool,
                    buffer,
                    type(range),
                    type("".index),
                    type(BaseException),
                    dict,
                    type(Ellipsis),
                    file,
                    float,
                    type(sys._getframe(0)),
                    xrange,
                    int,
                    long,
                    unicode,
                    tuple,
                    type(lambda: 3),
                    type(None),
                    type(object.__str__),
                    PySubType1,
                    PySubType2,
                    PySubType3,
                    ]:
            called = False
            
            class MyType(type):
                def __clrtype__(self):
                    global called
                    called = True
                    return x
            
            class X(object):
                __metaclass__ = MyType
            
            self.assertEqual(called, True) 
Example #22
Source File: test___clrtype.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def test_neg_clrtype_returns_nonsense_values(self):
        '''
        The __clrtype__ implementation returns invalid values.
        '''
        global called
        import System
        
        for x, expected_msg in [[[], "expected Type, got list"], 
                                [(None,), "expected Type, got tuple"], 
                                [True, "expected Type, got bool"], 
                                [False, "expected Type, got bool"], 
                                [3.14, "expected Type, got float"], 
                                ["a string", "expected Type, got str"],
                                [System.UInt16(32), "expected Type, got UInt16"],
                                [long(1), "expected Type, got long"],
                    ]:
            called = False
            
            class MyType(type):
                def __clrtype__(self):
                    global called
                    called = True
                    return x

            try:
                class X(object):
                    __metaclass__ = MyType
                Fail("Arbitrary return values of __clrtype__ should not be allowed: " + str(x))
            except TypeError as e:
                self.assertEqual(e.message,
                        expected_msg)
            finally:    
                self.assertEqual(called, True)
            
            
        #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=23244
        called = False
        
        class MyType(type):
            def __clrtype__(self):
                global called
                called = True
                return None
        
        try:
            class X(object):
                __metaclass__ = MyType
            Fail("Arbitrary return values of __clrtype__ are not allowed: ", + str(x))
        except ValueError as e:
            self.assertEqual(e.message, "__clrtype__ must return a type, not None")
        finally:
            self.assertEqual(called, True) 
Example #23
Source File: test___clrtype.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def test_clrtype_returns_existing_clr_types(self):
        '''
        Our implementation of __clrtype__ returns existing .NET types
        instead of subclassing from type or System.Type.
        '''
        global called
        import clr
        import System
        if is_netcoreapp:
            clr.AddReference("System.Collections")
            clr.AddReference("System.Data.Common")
        else:
            clr.AddReference("System.Data")
        
        types = [
                    System.Byte,
                    System.Int16,
                    System.UInt32,
                    System.Int32,
                    System.Int64,
                    System.Double,
                    System.Data.CommandType,
                    System.Data.Common.DataAdapter,
                    System.Boolean,
                    System.Char,
                    System.Decimal,
                    System.IntPtr,
                    System.Object,
                    System.String,
                    System.Collections.BitArray,
                    System.Collections.Generic.List[System.Char],
                    ]

        for x in types:
            called = False
            
            class MyType(type):
                def __clrtype__(self):
                    global called
                    called = True
                    return x
            
            class X(object):
                __metaclass__ = MyType
            
            self.assertEqual(called, True) 
Example #24
Source File: test___clrtype.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def test_clrtype_returns_existing_python_types(self):
        '''
        Our implementation of __clrtype__ returns pure-Python types
        instead of subclassing from type or System.Type and implementing
        __clrtype__.
        '''
        global called
        
        class PySubType1(type): pass
        class PySubType2(PySubType1): pass
        class PySubType3(PySubType2, PySubType1): pass
        
        for x in [
                    bool,
                    buffer,
                    type(range),
                    type("".index),
                    type(BaseException),
                    dict,
                    type(Ellipsis),
                    file,
                    float,
                    type(sys._getframe(0)),
                    xrange,
                    int,
                    long,
                    unicode,
                    tuple,
                    type(lambda: 3),
                    type(None),
                    type(object.__str__),
                    PySubType1,
                    PySubType2,
                    PySubType3,
                    ]:
            called = False
            
            class MyType(type):
                def __clrtype__(self):
                    global called
                    called = True
                    return x
            
            class X(object):
                __metaclass__ = MyType
            
            self.assertEqual(called, True) 
Example #25
Source File: test_missing.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def EmitArg(cg, arg):
    cg.ilg.Emit(OpCodes.Ldarg_0)

    TypeCode = System.TypeCode

    if arg.IsByRef:
        base = arg.GetElementType()
        if not base.IsValueType:
            cg.ilg.Emit(OpCodes.Ldind_Ref)
        else:
            tc = System.Type.GetTypeCode(base)
            if tc == TypeCode.Int32:
                cg.ilg.Emit(OpCodes.Ldind_I4)
            elif tc == TypeCode.Object:
                cg.ilg.Emit(OpCodes.Ldobj, base)
            elif tc == TypeCode.Boolean:
                cg.ilg.Emit(OpCodes.Ldind_I1)
            elif tc == TypeCode.Byte:
                cg.ilg.Emit(OpCodes.Ldind_U1)
            elif tc == TypeCode.Char:
                cg.ilg.Emit(OpCodes.Ldind_I2)
            elif tc == TypeCode.DateTime:
                cg.ilg.Emit(OpCodes.Ldobj, base)
            elif tc == TypeCode.DBNull: pass
            elif tc == TypeCode.Decimal:
                cg.ilg.Emit(OpCodes.Ldobj, base)
            elif tc == TypeCode.Double:
                cg.ilg.Emit(OpCodes.Ldind_R8)
            #elif tc == TypeCode.Empty: pass
            elif tc == TypeCode.Int16:
                cg.ilg.Emit(OpCodes.Ldind_I2)
            elif tc == TypeCode.Int64:
                cg.ilg.Emit(OpCodes.Ldind_I8)
            elif tc == TypeCode.SByte:
                cg.ilg.Emit(OpCodes.Ldind_I1)
            elif tc == TypeCode.Single:
                cg.ilg.Emit(OpCodes.Ldind_R4)
            #elif tc == TypeCode.String: pass
            elif tc == TypeCode.UInt16:
                cg.ilg.Emit(OpCodes.Ldind_U2)
            elif tc == TypeCode.UInt32:
                cg.ilg.Emit(OpCodes.Ldind_U4)
            elif tc == TypeCode.UInt64:
                cg.ilg.Emit(OpCodes.Ldind_I8)
            else:
                raise AssertionError("Unknown type", arg, base, tc) 
Example #26
Source File: test_missing.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def EmitTestMethod(tg, name, argType):
    cg = tg.DefineMethod(name, Reflection.MethodAttributes.Public | Reflection.MethodAttributes.Static, str, argType)
    pb = cg.mb.DefineParameter(1, Reflection.ParameterAttributes.In | Reflection.ParameterAttributes.Optional, "o");

    tostring = cg.ilg.DeclareLocal(str)

    baseType = argType
    if baseType.IsByRef:
        baseType = baseType.GetElementType()

    if not baseType.IsValueType:
        is_null = cg.ilg.DefineLabel()
        end = cg.ilg.DefineLabel()
        EmitArg(cg, argType)
        cg.ilg.Emit(OpCodes.Brfalse_S, is_null)
        cg.ilg.BeginExceptionBlock()
        EmitArg(cg, argType)
        cg.ilg.EmitCall(OpCodes.Callvirt, clr.GetClrType(object).GetMethod("ToString"), None)
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.BeginCatchBlock(clr.GetClrType(System.Exception))
        cg.ilg.Emit(OpCodes.Callvirt, clr.GetClrType(System.Exception).GetMethod("get_Message"))
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.Emit(OpCodes.Ldstr, "#EXCEPTION#")
        cg.ilg.Emit(OpCodes.Ldloc, tostring)
        cg.ilg.EmitCall(OpCodes.Call, clr.GetClrType(str).GetMethod("Concat", MakeArray(System.Type, clr.GetClrType(System.String), clr.GetClrType(System.String))), None)
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.EndExceptionBlock()
        cg.ilg.Emit(OpCodes.Br_S, end);
        cg.ilg.MarkLabel(is_null)
        cg.ilg.Emit(OpCodes.Ldstr, "(null)")
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.MarkLabel(end)
    else:
        cg.ilg.BeginExceptionBlock()
        EmitArg(cg, argType)
        cg.ilg.Emit(OpCodes.Box, baseType);
        cg.ilg.EmitCall(OpCodes.Callvirt, clr.GetClrType(object).GetMethod("ToString"), None)
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.BeginCatchBlock(clr.GetClrType(System.Exception))
        cg.ilg.Emit(OpCodes.Callvirt, clr.GetClrType(System.Exception).GetMethod("get_Message"))
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.Emit(OpCodes.Ldstr, "#EXCEPTION#")
        cg.ilg.Emit(OpCodes.Ldloc, tostring)
        cg.ilg.EmitCall(OpCodes.Call, clr.GetClrType(System.String).GetMethod("Concat", MakeArray(System.Type, clr.GetClrType(System.String), clr.GetClrType(System.String))), None)
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.EndExceptionBlock()

    cg.ilg.Emit(OpCodes.Ldstr, name + "$" + argType.FullName + "$")
    cg.ilg.Emit(OpCodes.Ldloc, tostring)
    cg.ilg.EmitCall(OpCodes.Call, clr.GetClrType(System.String).GetMethod("Concat", MakeArray(System.Type, clr.GetClrType(System.String), clr.GetClrType(System.String))), None)
    if trace:
        cg.ilg.Emit(OpCodes.Dup)
        cg.ilg.EmitCall(OpCodes.Call, clr.GetClrType(System.Console).GetMethod("WriteLine", MakeArray(System.Type, clr.GetClrType(System.String))), None)
    cg.ilg.Emit(OpCodes.Ret) 
Example #27
Source File: test_missing.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def EmitArg(cg, arg):
    cg.ilg.Emit(OpCodes.Ldarg_0)

    TypeCode = System.TypeCode

    if arg.IsByRef:
        base = arg.GetElementType()
        if not base.IsValueType:
            cg.ilg.Emit(OpCodes.Ldind_Ref)
        else:
            tc = System.Type.GetTypeCode(base)
            if tc == TypeCode.Int32:
                cg.ilg.Emit(OpCodes.Ldind_I4)
            elif tc == TypeCode.Object:
                cg.ilg.Emit(OpCodes.Ldobj, base)
            elif tc == TypeCode.Boolean:
                cg.ilg.Emit(OpCodes.Ldind_I1)
            elif tc == TypeCode.Byte:
                cg.ilg.Emit(OpCodes.Ldind_U1)
            elif tc == TypeCode.Char:
                cg.ilg.Emit(OpCodes.Ldind_I2)
            elif tc == TypeCode.DateTime:
                cg.ilg.Emit(OpCodes.Ldobj, base)
            elif tc == TypeCode.DBNull: pass
            elif tc == TypeCode.Decimal:
                cg.ilg.Emit(OpCodes.Ldobj, base)
            elif tc == TypeCode.Double:
                cg.ilg.Emit(OpCodes.Ldind_R8)
            #elif tc == TypeCode.Empty: pass
            elif tc == TypeCode.Int16:
                cg.ilg.Emit(OpCodes.Ldind_I2)
            elif tc == TypeCode.Int64:
                cg.ilg.Emit(OpCodes.Ldind_I8)
            elif tc == TypeCode.SByte:
                cg.ilg.Emit(OpCodes.Ldind_I1)
            elif tc == TypeCode.Single:
                cg.ilg.Emit(OpCodes.Ldind_R4)
            #elif tc == TypeCode.String: pass
            elif tc == TypeCode.UInt16:
                cg.ilg.Emit(OpCodes.Ldind_U2)
            elif tc == TypeCode.UInt32:
                cg.ilg.Emit(OpCodes.Ldind_U4)
            elif tc == TypeCode.UInt64:
                cg.ilg.Emit(OpCodes.Ldind_I8)
            else:
                raise AssertionError("Unknown type", arg, base, tc) 
Example #28
Source File: test_missing.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def EmitTestMethod(tg, name, argType):
    cg = tg.DefineMethod(name, Reflection.MethodAttributes.Public | Reflection.MethodAttributes.Static, str, argType)
    pb = cg.mb.DefineParameter(1, Reflection.ParameterAttributes.In | Reflection.ParameterAttributes.Optional, "o");

    tostring = cg.ilg.DeclareLocal(str)

    baseType = argType
    if baseType.IsByRef:
        baseType = baseType.GetElementType()

    if not baseType.IsValueType:
        is_null = cg.ilg.DefineLabel()
        end = cg.ilg.DefineLabel()
        EmitArg(cg, argType)
        cg.ilg.Emit(OpCodes.Brfalse_S, is_null)
        cg.ilg.BeginExceptionBlock()
        EmitArg(cg, argType)
        cg.ilg.EmitCall(OpCodes.Callvirt, clr.GetClrType(object).GetMethod("ToString"), None)
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.BeginCatchBlock(clr.GetClrType(System.Exception))
        cg.ilg.Emit(OpCodes.Callvirt, clr.GetClrType(System.Exception).GetMethod("get_Message"))
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.Emit(OpCodes.Ldstr, "#EXCEPTION#")
        cg.ilg.Emit(OpCodes.Ldloc, tostring)
        cg.ilg.EmitCall(OpCodes.Call, clr.GetClrType(str).GetMethod("Concat", MakeArray(System.Type, clr.GetClrType(System.String), clr.GetClrType(System.String))), None)
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.EndExceptionBlock()
        cg.ilg.Emit(OpCodes.Br_S, end);
        cg.ilg.MarkLabel(is_null)
        cg.ilg.Emit(OpCodes.Ldstr, "(null)")
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.MarkLabel(end)
    else:
        cg.ilg.BeginExceptionBlock()
        EmitArg(cg, argType)
        cg.ilg.Emit(OpCodes.Box, baseType);
        cg.ilg.EmitCall(OpCodes.Callvirt, clr.GetClrType(object).GetMethod("ToString"), None)
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.BeginCatchBlock(clr.GetClrType(System.Exception))
        cg.ilg.Emit(OpCodes.Callvirt, clr.GetClrType(System.Exception).GetMethod("get_Message"))
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.Emit(OpCodes.Ldstr, "#EXCEPTION#")
        cg.ilg.Emit(OpCodes.Ldloc, tostring)
        cg.ilg.EmitCall(OpCodes.Call, clr.GetClrType(System.String).GetMethod("Concat", MakeArray(System.Type, clr.GetClrType(System.String), clr.GetClrType(System.String))), None)
        cg.ilg.Emit(OpCodes.Stloc, tostring)
        cg.ilg.EndExceptionBlock()

    cg.ilg.Emit(OpCodes.Ldstr, name + "$" + argType.FullName + "$")
    cg.ilg.Emit(OpCodes.Ldloc, tostring)
    cg.ilg.EmitCall(OpCodes.Call, clr.GetClrType(System.String).GetMethod("Concat", MakeArray(System.Type, clr.GetClrType(System.String), clr.GetClrType(System.String))), None)
    if trace:
        cg.ilg.Emit(OpCodes.Dup)
        cg.ilg.EmitCall(OpCodes.Call, clr.GetClrType(System.Console).GetMethod("WriteLine", MakeArray(System.Type, clr.GetClrType(System.String))), None)
    cg.ilg.Emit(OpCodes.Ret) 
Example #29
Source File: test___clrtype__.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def test_clrtype_returns_existing_clr_types(self):
        '''
        Our implementation of __clrtype__ returns existing .NET types
        instead of subclassing from type or System.Type.
        '''
        global called
        import clr
        import System
        if is_netcoreapp:
            clr.AddReference("System.Collections")
            clr.AddReference("System.Data.Common")
        else:
            clr.AddReference("System.Data")
        
        types = [
                    System.Byte,
                    System.Int16,
                    System.UInt32,
                    System.Int32,
                    System.Int64,
                    System.Double,
                    System.Data.CommandType,
                    System.Data.Common.DataAdapter,
                    System.Boolean,
                    System.Char,
                    System.Decimal,
                    System.IntPtr,
                    System.Object,
                    System.String,
                    System.Collections.BitArray,
                    System.Collections.Generic.List[System.Char],
                    ]

        for x in types:
            called = False
            
            class MyType(type):
                def __clrtype__(self):
                    global called
                    called = True
                    return x
            
            class X(object):
                __metaclass__ = MyType
            
            self.assertEqual(called, True)