def readFromDatasetWithCompoundType(dset): mtype = createMemType() sizeof = H5T.getSize(mtype) dspace = H5D.getSpace(dset) npoints = H5S.getSimpleExtentNPoints(dspace) shape = Array[Int64]((npoints * sizeof, )) byteArray = Array.CreateInstance(Byte, shape) H5D.read(dset, mtype, H5Array[Byte](byteArray)) ms = MemoryStream(byteArray) reader = BinaryReader(ms) for i in range(npoints): if IntPtr.Size == 8: print '%d,%s,%.2f,%.2f' % (reader.ReadInt32( ), Marshal.PtrToStringAnsi(IntPtr( reader.ReadInt64())), reader.ReadDouble(), reader.ReadDouble()) else: print '%d,%s,%.2f,%.2f' % (reader.ReadInt32( ), Marshal.PtrToStringAnsi(IntPtr( reader.ReadInt32())), reader.ReadDouble(), reader.ReadDouble()) H5S.close(dspace) H5T.close(mtype) return None
def testWritePtrField(self): data = Marshal.AllocHGlobal(Marshal.SizeOf(PyObject())) CPyMarshal.Zero(data, Marshal.SizeOf(PyObject())) CPyMarshal.WritePtrField(data, PyObject, "ob_type", IntPtr(12345)) dataStruct = PtrToStructure(data, PyObject) self.assertEquals(dataStruct.ob_type, IntPtr(12345), "failed to write") Marshal.FreeHGlobal(data)
def storm_run(loader, net, epoch, num_classes, behavior): if (behavior == 0): net.SetTrainMode() else: net.SetPredictMode() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() end = time.time() outputs = torch.zeros([args.train_batch, num_classes], dtype=torch.float) p_output = IntPtr.op_Explicit(Int64(outputs.data_ptr())) net.Init() bar = Bar('Processing', max=len(loader)) for batch_idx, (inputs, targets) in enumerate(loader): # measure data loading time data_time.update(time.time() - end) #print(inputs.shape) ## cpu data. p_input = IntPtr.op_Explicit(Int64(inputs.data_ptr())) p_target = IntPtr.op_Explicit(Int64(targets.data_ptr())) # compute output #outputs = model(inputs) #loss = criterion(outputs, targets) loss = net.Run(p_input, p_target, p_output, args.train_batch) # measure accuracy and record loss prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5)) losses.update(loss, inputs.size(0)) top1.update(prec1, inputs.size(0)) top5.update(prec5, inputs.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() # plot progress bar.suffix = '({batch}/{size}) Data: {data:.3f}s | Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} | top1: {top1: .4f} | top5: {top5: .4f}'.format( batch=batch_idx + 1, size=len(loader), data=data_time.avg, bt=batch_time.avg, total=bar.elapsed_td, eta=bar.eta_td, loss=losses.avg, top1=top1.avg, top5=top5.avg, ) bar.next() bar.finish() net.Complete() return (losses.avg, top1.avg)
def testReadPtr(self): data = Marshal.AllocHGlobal(CPyMarshal.PtrSize) Marshal.WriteIntPtr(data, IntPtr(0)) self.assertEquals(CPyMarshal.ReadPtr(data), IntPtr(0), "wrong") Marshal.WriteIntPtr(data, IntPtr(100001)) self.assertEquals(CPyMarshal.ReadPtr(data), IntPtr(100001), "wrong") Marshal.FreeHGlobal(data)
def testReadPtrField(self): data = Marshal.AllocHGlobal(Marshal.SizeOf(PyTypeObject())) CPyMarshal.Zero(data, Marshal.SizeOf(PyTypeObject())) CPyMarshal.WritePtrField(data, PyTypeObject, "tp_doc", IntPtr(12345)) self.assertEquals( CPyMarshal.ReadPtrField(data, PyTypeObject, "tp_doc"), IntPtr(12345), "failed to read") Marshal.FreeHGlobal(data)
def testErrorCaseSecondArg(self, mapper, addToCleanup): part1Ptr = mapper.Store(17) mapper.IncRef(part1Ptr) # avoid garbage collection startingRefCnt = mapper.RefCount(part1Ptr) part2Ptr = mapper.Store("three") stringPtrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(IntPtr())) addToCleanup(lambda: Marshal.FreeHGlobal(stringPtrPtr)) Marshal.WriteIntPtr(stringPtrPtr, part1Ptr) mapper.PyString_Concat(stringPtrPtr, part2Ptr) self.assertMapperHasError(mapper, TypeError) self.assertEquals(Marshal.ReadIntPtr(stringPtrPtr), IntPtr(0)) self.assertEquals(startingRefCnt - mapper.RefCount(part1Ptr), 1)
def testCallsTypeAllocFunction(self, mapper, addToCleanUp): calls = [] def Alloc(typePtr, nItems): calls.append((typePtr, nItems)) return IntPtr(999) typeSpec = { "tp_alloc": Alloc, } typePtr, deallocType = MakeTypePtr(mapper, typeSpec) addToCleanUp(deallocType) result = mapper.PyType_GenericNew(typePtr, IntPtr(222), IntPtr(333)) self.assertEquals(result, IntPtr(999), "did not use type's tp_alloc function") self.assertEquals(calls, [(typePtr, 0)], "passed wrong args")
def testPySequence_Repeat_TypeWithSequenceRepeat(self, mapper, addToCleanUp): RESULT_PTR = IntPtr(123) calls = [] def RepeatFunc(selfPtr, count): calls.append((selfPtr, count)) return RESULT_PTR def Multiply(selfPtr, otherPtr): raise Exception("don't multiply if we can repeat!") seqPtr, deallocSeq = MakeNumSeqMapMethods(PySequenceMethods, {'sq_repeat': RepeatFunc}) addToCleanUp(deallocSeq) numPtr, deallocNum = MakeNumSeqMapMethods(PyNumberMethods, {'nb_multiply': Multiply}) addToCleanUp(deallocNum) typeSpec = { "tp_as_sequence": seqPtr, "tp_as_number": numPtr, } typePtr, deallocType = MakeTypePtr(mapper, typeSpec) addToCleanUp(deallocType) instance = mapper.Retrieve(typePtr)() instancePtr = mapper.Store(instance) self.assertEquals(mapper.PySequence_Repeat(instancePtr, 3), RESULT_PTR) self.assertEquals(calls, [(instancePtr, 3)])
def testShrink(self): allocs = [] frees = [] mapper = PythonMapper(GetAllocatingTestAllocator(allocs, frees)) deallocTypes = CreateTypes(mapper) del allocs[:] oldLength = 365 newLength = 20 ptrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(IntPtr())) try: strPtr = mapper.PyString_FromStringAndSize(IntPtr.Zero, oldLength) Marshal.WriteIntPtr(ptrPtr, strPtr) baseSize = Marshal.SizeOf(PyStringObject()) self.assertEquals(allocs, [(strPtr, oldLength + baseSize)], "allocated wrong") self.assertEquals(mapper._PyString_Resize(ptrPtr, newLength), 0, "bad return on success") self.assertHasStringType(strPtr, mapper) self.assertStringObjectHasLength(strPtr, newLength) self.assertEquals(allocs, [(strPtr, oldLength + baseSize)], "unexpected extra alloc") self.assertEquals(frees, [], "unexpected frees") finally: mapper.Dispose() Marshal.FreeHGlobal(ptrPtr) deallocTypes()
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, webview_ready): self.Text = title self.AutoScaleBaseSize = Size(5, 13) self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) # Application icon try: # Try loading an icon embedded in the exe file. This will crash when frozen with PyInstaller handler = windll.kernel32.GetModuleHandleW(None) icon_handler = windll.user32.LoadIconW(handler, 1) self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handler))) except: pass self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if fullscreen: self.toggle_fullscreen()
def testBufferProtocol(self, mapper, later): # should all be implemented in C really, but weaving cpy string type into # our code feels too much like hard work for now strPtr = mapper.PyString_Type bufPtr = CPyMarshal.ReadPtrField(strPtr, PyTypeObject, 'tp_as_buffer') self.assertNotEquals(bufPtr, IntPtr.Zero) getreadbuffer = CPyMarshal.ReadFunctionPtrField( bufPtr, PyBufferProcs, 'bf_getreadbuffer', dgt_int_ptrintptr) getwritebuffer = CPyMarshal.ReadFunctionPtrField( bufPtr, PyBufferProcs, 'bf_getwritebuffer', dgt_int_ptrintptr) getcharbuffer = CPyMarshal.ReadFunctionPtrField( bufPtr, PyBufferProcs, 'bf_getcharbuffer', dgt_int_ptrintptr) getsegcount = CPyMarshal.ReadFunctionPtrField(bufPtr, PyBufferProcs, 'bf_getsegcount', dgt_int_ptrptr) ptrptr = Marshal.AllocHGlobal(Marshal.SizeOf(IntPtr())) later(lambda: Marshal.FreeHGlobal(ptrptr)) strptr = mapper.Store("hullo") for getter in (getreadbuffer, getcharbuffer): self.assertEquals(getter(strptr, 0, ptrptr), 5) self.assertEquals( CPyMarshal.ReadPtr(ptrptr), CPyMarshal.GetField(strptr, PyStringObject, 'ob_sval')) self.assertEquals(getter(strptr, 1, ptrptr), -1) self.assertMapperHasError(mapper, SystemError) self.assertEquals(getwritebuffer(strptr, 0, ptrptr), -1) self.assertMapperHasError(mapper, SystemError) self.assertEquals(getsegcount(strptr, ptrptr), 1) self.assertEquals(CPyMarshal.ReadInt(ptrptr), 5) self.assertEquals(getsegcount(strptr, IntPtr.Zero), 1)
def testInternExisting(self, mapper, addToCleanUp): testString = "mars needs women" + self.getStringWithValues(1, 256) bytes = self.byteArrayFromString(testString) testData = self.ptrFromByteArray(bytes) sp1 = mapper.PyString_FromString(testData) addToCleanUp(lambda: Marshal.FreeHGlobal(sp1p)) sp2 = mapper.PyString_InternFromString(testData) addToCleanUp(lambda: Marshal.FreeHGlobal(testData)) self.assertNotEquals(sp1, sp2) self.assertFalse(mapper.Retrieve(sp1) is mapper.Retrieve(sp2)) self.assertEquals(mapper.RefCount(sp1), 1) self.assertEquals( mapper.RefCount(sp2), 2, 'failed to grab extra reference to induce immortality') mapper.IncRef(sp1) sp1p = Marshal.AllocHGlobal(Marshal.SizeOf(IntPtr())) CPyMarshal.WritePtr(sp1p, sp1) mapper.PyString_InternInPlace(sp1p) sp1i = CPyMarshal.ReadPtr(sp1p) self.assertEquals(sp1i, sp2, 'failed to intern') self.assertTrue(mapper.Retrieve(sp1i) is mapper.Retrieve(sp2)) self.assertEquals(mapper.RefCount(sp1), 1, 'failed to decref old string') self.assertEquals(mapper.RefCount(sp2), 3, 'failed to incref interned string')
def __init__(self, window): self.uid = window.uid self.pywebview_window = window self.real_url = None self.Text = window.title self.ClientSize = Size(window.width, window.height) self.MinimumSize = Size(window.min_size[0], window.min_size[1]) self.BackColor = ColorTranslator.FromHtml(window.background_color) if window.x is not None and window.y is not None: self.move(window.x, window.y) else: self.StartPosition = WinForms.FormStartPosition.CenterScreen self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not window.resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle(IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.shown = window.shown self.loaded = window.loaded self.url = window.url self.text_select = window.text_select self.is_fullscreen = False if window.fullscreen: self.toggle_fullscreen() if window.frameless: self.frameless = window.frameless self.FormBorderStyle = 0 if is_cef: CEF.create_browser(window, self.Handle.ToInt32(), BrowserView.alert) elif is_edge: self.browser = BrowserView.EdgeHTML(self, window) else: self.browser = BrowserView.MSHTML(self, window) self.Shown += self.on_shown self.FormClosed += self.on_close if is_cef: self.Resize += self.on_resize if window.confirm_close: self.FormClosing += self.on_closing
def __init__(self, window): self.uid = window.uid self.pywebview_window = window self.url = None self.Text = window.title self.Size = Size(window.initial_width, window.initial_height) self.MinimumSize = Size(window.min_size[0], window.min_size[1]) self.BackColor = ColorTranslator.FromHtml(window.background_color) if window.initial_x is not None and window.initial_y is not None: self.move(window.initial_x, window.initial_y) else: self.StartPosition = WinForms.FormStartPosition.CenterScreen self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not window.resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False if window.minimized: self.WindowState = WinForms.FormWindowState.Minimized # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_path = os.path.join(os.path.dirname(os.path.realpath(importlib.util.find_spec("bcml").origin)), "data", "bcml.ico") icon_handle = windll.shell32.ExtractIconW(handle, icon_path, 0) if icon_handle != 0: self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handle)) ).Clone() windll.user32.DestroyIcon(icon_handle) self.closed = window.closed self.closing = window.closing self.shown = window.shown self.loaded = window.loaded self.url = window.url self.text_select = window.text_select self.on_top = window.on_top self.is_fullscreen = False if window.fullscreen: self.toggle_fullscreen() if window.frameless: self.frameless = window.frameless self.FormBorderStyle = 0 CEF.create_browser(window, self.Handle.ToInt32(), BrowserView.alert) self.Shown += self.on_shown self.FormClosed += self.on_close self.FormClosing += self.on_closing self.Resize += self.on_resize
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, webview_ready): self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) self.BackColor = ColorTranslator.FromHtml(background_color) if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill self.web_browser.ScriptErrorsSuppressed = True self.web_browser.IsWebBrowserContextMenuEnabled = False self.web_browser.WebBrowserShortcutsEnabled = False # HACK. Hiding the WebBrowser is needed in order to show a non-default background color. Tweaking the Visible property # results in showing a non-responsive control, until it is loaded fully. To avoid this, we need to disable this behaviour # for the default background color. if background_color != '#FFFFFF': self.web_browser.Visible = False self.first_load = True else: self.first_load = False self.cancel_back = False self.web_browser.PreviewKeyDown += self.on_preview_keydown self.web_browser.Navigating += self.on_navigating self.web_browser.DocumentCompleted += self.on_document_completed if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if confirm_quit: self.FormClosing += self.on_closing if fullscreen: self.toggle_fullscreen()
def testPyListTypeField_tp_dealloc(self): calls = [] class MyPM(PythonMapper): def IC_PyList_Dealloc(self, listPtr): calls.append(listPtr) mapper = MyPM() typeBlock = Marshal.AllocHGlobal(Marshal.SizeOf(PyTypeObject)) mapper.RegisterData("PyList_Type", typeBlock) gcwait() # this will make the function pointers invalid if we forgot to store references to the delegates deallocDgt = CPyMarshal.ReadFunctionPtrField(typeBlock, PyTypeObject, "tp_dealloc", dgt_void_ptr) deallocDgt(IntPtr(12345)) self.assertEquals(calls, [IntPtr(12345)], "wrong calls") mapper.Dispose() Marshal.FreeHGlobal(typeBlock)
def runarx(doc): res = edx.entsel("请选择图元") if not res.ok(): return name = adsname() GetAdsName(byref(name), res.ObjectId) rb = acdb.ResultBuffer((acdb.TypedValue(int(acrx.LispDataType.Text), "*"), )) ip = EntGetX(name, rb.UnmanagedObject) from System import IntPtr rb = acdb.ResultBuffer.Create(IntPtr(ip), True) print(rb)
def testReadFunctionPtrField(self): data = Marshal.AllocHGlobal(Marshal.SizeOf(PyTypeObject())) CPyMarshal.Zero(data, Marshal.SizeOf(PyTypeObject())) calls = [] def TestFunc(selfPtr, argsPtr, kwargsPtr): calls.append((selfPtr, argsPtr, kwargsPtr)) return 123 self.testDgt = dgt_int_ptrptrptr(TestFunc) CPyMarshal.WriteFunctionPtrField(data, PyTypeObject, "tp_init", self.testDgt) readDgt = CPyMarshal.ReadFunctionPtrField(data, PyTypeObject, "tp_init", dgt_int_ptrptrptr) args = (IntPtr(111), IntPtr(222), IntPtr(333)) self.assertEquals(readDgt(*args), 123, "not hooked up") self.assertEquals(calls, [args], "not hooked up")
def writeDatasets(h5file): dtype = H5T.copy(H5T.H5Type.NATIVE_INT) shape = Array[Int64]((2, 9)) dspacev = H5S.create_simple(shape.Length, shape) dsetv = H5D.create(h5file, 'MATRIX', dtype, dspacev) data = Array.CreateInstance(Int32, shape) data[0, 0] = data[0, 1] = data[1, 0] = 1 data[0, 2] = data[1, 1] = data[1, 2] = 2 data[0, 3] = data[0, 4] = data[1, 3] = 3 data[0, 5] = data[1, 4] = data[1, 5] = 4 data[0, 6] = data[0, 7] = data[1, 6] = 5 data[0, 8] = data[1, 7] = data[1, 8] = 6 H5D.write(dsetv, dtype, H5Array[Int32](data)) H5T.close(dtype) dtype = H5T.copy(H5T.H5Type.STD_REF_DSETREG) shape = Array[Int64]((2, )) dspacer = H5S.create_simple(shape.Length, shape) dsetr = H5D.create(h5file, 'REGION_REFERENCES', dtype, dspacer) start = Array[Int64]((0, 3)) count = Array[Int64]((2, 3)) H5S.selectHyperslab(dspacev, H5S.SelectOperator.SET, start, count) rr = Array.CreateInstance(RegionReference, 2) rr[0] = H5R.createRegionReference(h5file, 'MATRIX', dspacev) coord = Array.CreateInstance(Int64, 6) coord[0] = coord[1] = coord[4] = 0 coord[2] = 1 coord[3] = 6 coord[5] = 8 H5S.selectNone(dspacev) H5S.selectElements(dspacev, H5S.SelectOperator.SET, IntPtr(3), coord) rr[1] = H5R.createRegionReference(h5file, 'MATRIX', dspacev) nBytes = RegionReference.SizeInBytes data = Array.CreateInstance(Byte, rr.Length * nBytes) for i in range(rr.Length): Array.Copy(rr[i].ToByteArray(), 0, data, i * nBytes, nBytes) H5D.write(dsetr, dtype, H5Array[Byte](data)) H5T.close(dtype) H5D.close(dsetv) H5S.close(dspacev) H5D.close(dsetr) H5S.close(dspacer) return None
def lisp(cls, *args): accore = cls.load("accore.dll") if not cls._lispfuncs.__contains__(args[0]): cls._lispfuncs.append(args[0]) accore.ads_queueexpr("(vl-acad-defun '%s)\n" % args[0]) d = acdb.ResultBuffer(tuple(conv.ToTypedValue(x) for x in args)) from ctypes import c_long, byref ip = c_long() res = accore.acedInvoke(d.UnmanagedObject, byref(ip)) if res != -5001: from System import IntPtr return acdb.ResultBuffer.Create(IntPtr(ip.value), True)
def __init__(self, uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, frameless, webview_ready): self.uid = uid self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) self.BackColor = ColorTranslator.FromHtml(background_color) self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle(IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.webview_ready = webview_ready self.load_event = Event() self.background_color = background_color self.url = url self.is_fullscreen = False if fullscreen: self.toggle_fullscreen() if frameless: self.frameless = frameless self.FormBorderStyle = 0 if is_cef: CEF.create_browser(self.uid, self.Handle.ToInt32(), BrowserView.alert, url, js_api) else: self._create_mshtml_browser(url, js_api, debug) self.text_select = text_select self.Shown += self.on_shown self.FormClosed += self.on_close if is_cef: self.Resize += self.on_resize if confirm_quit: self.FormClosing += self.on_closing
def _fetch_getdev(self): clist = self._clean_channel_list() if self._inbuffer == None: return None #This conversion is much faster than doing # v=array(list(buf.GetDataAsVolts())) buf = self._inbuffer fullsize = buf.BufferSizeInSamples validsize = buf.ValidSamples v=np.ndarray(validsize, dtype=float) Marshal.Copy(buf.GetDataAsVolts(), 0, IntPtr.op_Explicit(Int32(v.ctypes.data)), len(v)) num_channel = len(clist) if num_channel != 1 and self.nb_samples.getcache() != 1: v.shape = (-1, num_channel) v = v.T return v
def _fetch_getdev(self): clist = self._clean_channel_list() if self._inbuffer is None: return None #This conversion is much faster than doing # v=array(list(buf.GetDataAsVolts())) buf = self._inbuffer fullsize = buf.BufferSizeInSamples validsize = buf.ValidSamples v = np.ndarray(validsize, dtype=float) Marshal.Copy(buf.GetDataAsVolts(), 0, IntPtr.op_Explicit(Int64(v.ctypes.data)), len(v)) num_channel = len(clist) if num_channel != 1 and self.nb_samples.getcache() != 1: v.shape = (-1, num_channel) v = v.T return v
def testBasic(self, mapper, addToCleanup): part1Ptr = mapper.Store("one two") mapper.IncRef(part1Ptr) # avoid garbage collection part2Ptr = mapper.Store(" three") startingRefCnt = mapper.RefCount(part1Ptr) stringPtrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(IntPtr())) addToCleanup(lambda: Marshal.FreeHGlobal(stringPtrPtr)) Marshal.WriteIntPtr(stringPtrPtr, part1Ptr) mapper.PyString_Concat(stringPtrPtr, part2Ptr) self.assertMapperHasError(mapper, None) newStringPtr = Marshal.ReadIntPtr(stringPtrPtr) self.assertEquals(mapper.Retrieve(newStringPtr), "one two three") self.assertEquals(startingRefCnt - mapper.RefCount(part1Ptr), 1)
def testGrow(self): allocs = [] frees = [] mapper = PythonMapper(GetAllocatingTestAllocator(allocs, frees)) deallocTypes = CreateTypes(mapper) del allocs[:] oldLength = 20 testString = "slings and arrows" + self.getStringWithValues(0, 256) newLength = len(testString) oldStrPtr = mapper.PyString_FromStringAndSize(IntPtr.Zero, oldLength) ptrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(IntPtr())) try: Marshal.WriteIntPtr(ptrPtr, oldStrPtr) newStrPtr = IntPtr.Zero baseSize = Marshal.SizeOf(PyStringObject()) self.assertEquals(allocs, [(oldStrPtr, oldLength + baseSize)], "allocated wrong") self.assertEquals(mapper._PyString_Resize(ptrPtr, newLength), 0, "bad return on success") newStrPtr = Marshal.ReadIntPtr(ptrPtr) expectedAllocs = [(oldStrPtr, oldLength + baseSize), (newStrPtr, newLength + baseSize)] self.assertEquals(allocs, expectedAllocs, "allocated wrong") self.assertEquals(frees, [oldStrPtr], "did not free unused memory") self.assertHasStringType(newStrPtr, mapper) self.assertStringObjectHasLength(newStrPtr, newLength) testBytes = self.byteArrayFromString(testString) self.fillStringDataWithBytes(newStrPtr, testBytes) self.assertEquals(mapper.Retrieve(newStrPtr), testString, "failed to read string data") if oldStrPtr != newStrPtr: # this would otherwise fail (very, very rarely) self.assertEquals(oldStrPtr in frees, True) finally: mapper.Dispose() Marshal.FreeHGlobal(ptrPtr) deallocTypes()
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, webview_ready): self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill self.web_browser.ScriptErrorsSuppressed = True self.web_browser.IsWebBrowserContextMenuEnabled = False self.cancel_back = False self.web_browser.PreviewKeyDown += self.on_preview_keydown self.web_browser.Navigating += self.on_navigating if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if confirm_quit: self.FormClosing += self.on_closing if fullscreen: self.toggle_fullscreen()
def find_element_by_handle(self, hex_or_int_handle): ''' use dynamic handle to find element usage: elem = find_element(AutomationId = "1",Name = "OK",ClassName = "Button") hex_or_int_handle = elem.getProp("NativeWindowHandle") elem = find_element_by_handle(hex_or_int_handle) ''' try: handle = hex_or_int_handle if isinstance(hex_or_int_handle, str): handle = int(hex_or_int_handle, 16);# 16进制转为 10进制; hex(123456)->10进制转换16进制 if handle == 0: return automation_element_obj = FromHandle(IntPtr(handle)) return WinWPFDriver(automation_element_obj) except: return
def testSizes(self, mapper, _): self.assertSizes(mapper.PyBaseObject_Type, Marshal.SizeOf(PyObject())) self.assertSizes(mapper.PyType_Type, Marshal.SizeOf(PyTypeObject())) self.assertSizes(mapper.PyTuple_Type, Marshal.SizeOf(PyTupleObject()), Marshal.SizeOf(IntPtr())) # bigger than necessary self.assertSizes(mapper.PyString_Type, Marshal.SizeOf(PyStringObject()) - 1, Marshal.SizeOf(Byte())) self.assertSizes(mapper.PyList_Type, Marshal.SizeOf(PyListObject())) self.assertSizes(mapper.PySlice_Type, Marshal.SizeOf(PySliceObject())) self.assertSizes(mapper.PyMethod_Type, Marshal.SizeOf(PyMethodObject())) self.assertSizes(mapper.PyInt_Type, Marshal.SizeOf(PyIntObject())) self.assertSizes(mapper.PyFloat_Type, Marshal.SizeOf(PyFloatObject())) self.assertSizes(mapper.PyComplex_Type, Marshal.SizeOf(PyComplexObject())) self.assertSizes(mapper.PyClass_Type, Marshal.SizeOf(PyClassObject())) self.assertSizes(mapper.PyInstance_Type, Marshal.SizeOf(PyInstanceObject()))
def writeVlenData(h5file): dtype = H5T.vlenCreate(H5T.H5Type.NATIVE_INT) array = range(16) npoints = len(array) shape = Array[Int64]((npoints, )) dspace = H5S.create_simple(shape.Length, shape) dset = H5D.create(h5file, 'Vlen Dataset', dtype, dspace) wdata = Array.CreateInstance(hvl_t, npoints) sizeofInt = 4 for i in range(npoints): nElems = array[i] + 1 nBytes = nElems * sizeofInt # the data to be written (array of length i+1 with all elements = i) data = Array.CreateInstance(Byte, nBytes) for j in range(nElems): Array.Copy(System.BitConverter.GetBytes(i), 0, data, j * sizeofInt, sizeofInt) # allocate and copy to array in unmanaged memory mem = Marshal.AllocHGlobal(nBytes) Marshal.Copy(data, 0, mem, nBytes) wdata[i] = VLen(IntPtr(nElems), mem).To_hvl_t() H5D.write(dset, dtype, H5Array[hvl_t](wdata)) # free unmanaged buffer space for i in range(npoints): vl = VLen(wdata[i]) Marshal.FreeHGlobal(vl.Pointer) H5D.close(dset) H5S.close(dspace) H5T.close(dtype) return None
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, webview_ready): self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle(IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill self.web_browser.ScriptErrorsSuppressed = True self.web_browser.IsWebBrowserContextMenuEnabled = False self.cancel_back = False self.web_browser.PreviewKeyDown += self.on_preview_keydown self.web_browser.Navigating += self.on_navigating if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if confirm_quit: self.FormClosing += self.on_closing if fullscreen: self.toggle_fullscreen()
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, webview_ready): self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon try: # Try loading an icon embedded in the exe file. This will crash when frozen with PyInstaller handler = windll.kernel32.GetModuleHandleW(None) icon_handler = windll.user32.LoadIconW(handler, 1) self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handler))) except: pass self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill self.web_browser.ScriptErrorsSuppressed = True self.web_browser.IsWebBrowserContextMenuEnabled = False if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if confirm_quit: self.FormClosing += self.on_closing if fullscreen: self.toggle_fullscreen()
def testErrorHandling(self): allocs = [] frees = [] mapper = PythonMapper(GetAllocatingTestAllocator(allocs, frees)) deallocTypes = CreateTypes(mapper) del allocs[:] ptrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(IntPtr())) try: data = mapper.PyString_FromStringAndSize(IntPtr.Zero, 365) Marshal.WriteIntPtr(ptrPtr, data) baseSize = Marshal.SizeOf(PyStringObject()) self.assertEquals(allocs, [(data, 365 + baseSize)], "allocated wrong") self.assertEquals(mapper._PyString_Resize(ptrPtr, 2000000000), -1, "bad return on error") self.assertEquals(type(mapper.LastException), MemoryError, "wrong exception type") self.assertTrue(data in frees, "did not deallocate") finally: mapper.Dispose() Marshal.FreeHGlobal(ptrPtr) deallocTypes()