void Update() { if (state == 0) { AndroidJavaClass UnityOpenCVLoaderJava = new AndroidJavaClass(UNITY_OPENCV_LOADER); var b = UnityOpenCVLoaderJava.CallStatic<Boolean>("isSuccess"); if (b) { state = 1; } } else if (state == 1) { if (cameraInstance == IntPtr.Zero) cameraInstance = CreateCameraInstance (); if (Open (cameraInstance, 0, width, height)) { texture = new Texture2D (width, height, TextureFormat.ARGB32, false); pixels = texture.GetPixels32 (); pixelsHandle = GCHandle.Alloc (pixels, GCHandleType.Pinned); pixelsPtr = pixelsHandle.AddrOfPinnedObject (); GetComponent<Renderer>().material.mainTexture = texture; state = 2; } else { state = -1; } } else if (state == 2) { getCameraTexture (cameraInstance, pixelsPtr, width, height); texture.SetPixels32 (pixels); texture.Apply (); } }
static void CreateSecondBridge () { Bridge b = new Bridge() { __test = 1, id = "second", }; weak_track_handle2 = GCHandle.Alloc (b, GCHandleType.WeakTrackResurrection); }
public static int Main() { int[] arr = new int[1000]; GCHandle[] arrhandle = new GCHandle[10000]; // array of handles to the same object IntPtr[] oldaddress = new IntPtr[10000]; // store old addresses IntPtr[] newaddress = new IntPtr[10000]; // store new addresses for (int i = 0; i < 10000; i++) { arrhandle[i] = GCUtil.Alloc(arr, GCHandleType.Pinned); oldaddress[i] = GCUtil.AddrOfPinnedObject(arrhandle[i]); } GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < 10000; i++) { newaddress[i] = GCUtil.AddrOfPinnedObject(arrhandle[i]); } for (int i = 0; i < 10000; i++) { if (oldaddress[i] != newaddress[i]) { Console.WriteLine("Test failed"); return 1; } } Console.WriteLine("Test passed"); return 100; }
private static AKRESULT DoLoadBank(string in_bankPath) { ms_www = new WWW(in_bankPath); while( ! ms_www.isDone ) { #if ! UNITY_METRO System.Threading.Thread.Sleep(WaitMs); #endif // #if ! UNITY_METRO } uint in_uInMemoryBankSize = 0; try { ms_pinnedArray = GCHandle.Alloc(ms_www.bytes, GCHandleType.Pinned); ms_pInMemoryBankPtr = ms_pinnedArray.AddrOfPinnedObject(); in_uInMemoryBankSize = (uint)ms_www.bytes.Length; } catch { return AKRESULT.AK_Fail; } AKRESULT result = AkSoundEngine.LoadBank(ms_pInMemoryBankPtr, in_uInMemoryBankSize, out ms_bankID); return result; }
// Update is called once per frame void Update() { // off-screen rendering var camtex = RenderTexture.GetTemporary (camWidth, camHeight, 24, RenderTextureFormat.Default, RenderTextureReadWrite.Default, 1); myCamera.targetTexture = camtex; myCamera.Render (); RenderTexture.active = camtex; tex.ReadPixels (new Rect (0, 0, camtex.width, camtex.height), 0, 0); tex.Apply (); // Convert texture to ptr texturePixels_ = tex.GetPixels32(); texturePixelsHandle_ = GCHandle.Alloc(texturePixels_, GCHandleType.Pinned); texturePixelsPtr_ = texturePixelsHandle_.AddrOfPinnedObject(); // Show a window fullWindow (windowName, displayNum, texturePixelsPtr_, camWidth, camHeight); texturePixelsHandle_.Free(); RenderTexture.active = null; RenderTexture.ReleaseTemporary (camtex); myCamera.targetTexture = null; }
private void CreateBuffer(int width, int height) { // Free buffer if it's too small if (_frameHandle.IsAllocated && _frameData != null) { if (_frameData.Length < _frameWidth * _frameHeight) { FreeBuffer(); } } if (_frameData == null) { _frameWidth = width; _frameHeight = height; _frameData = new Color32[_frameWidth * _frameHeight]; _frameHandle = GCHandle.Alloc(_frameData, GCHandleType.Pinned); _framePointer = _frameHandle.AddrOfPinnedObject(); #if TEXTURETEST _testTexture = new Texture2D(_frameWidth ,_frameHeight, TextureFormat.ARGB32, false, false); _testTexture.Apply(false, false); #endif } }
static void CreateFirstBridge () { Bridge b = new Bridge() { __test = 0, id = "first", }; weak_track_handle = GCHandle.Alloc (b, GCHandleType.WeakTrackResurrection); }
public static void RegisterCommandCallback(CommandCallbackDelegate fun) { _gcHandle = GCHandle.Alloc(fun); if (IntPtr.Size == 8) RegisterCommandCallback_x64(fun); else RegisterCommandCallback_x86(fun); }
// Use this for initialization void Start () { camera_ = getCamera(device); setCameraProp(camera_, width, height, fps); texture_ = new Texture2D(width, height, TextureFormat.ARGB32, false); pixels_ = texture_.GetPixels32(); pixels_handle_ = GCHandle.Alloc(pixels_, GCHandleType.Pinned); pixels_ptr_ = pixels_handle_.AddrOfPinnedObject(); GetComponent<Renderer>().material.mainTexture = texture_; }
public Matrix(int size) { if (!_validSizes.Contains(size)) throw new ArgumentOutOfRangeException("size"); _size = size; _data = new int[size * size]; _dataPtrHandle = GCHandle.Alloc(_data, GCHandleType.Pinned); _dataPtr = (int*)_dataPtrHandle.AddrOfPinnedObject().ToPointer(); }
public CreateObj() { obj = new Dummy(); Console.WriteLine("Allocating a Weak handle to object.."); handle = GCHandle.Alloc(obj, GCHandleType.Weak); // making a copy of the handle copy = handle; }
static void alloc_many() { int small_count = count / 2; GCHandle[] more = new GCHandle [small_count]; int i; for (i = 0; i < small_count; ++i) { GCHandleType t = (GCHandleType) (i & 3); more [i] = GCHandle.Alloc (i, t); } for (i = 0; i < small_count; ++i) { more [i].Free (); } Console.WriteLine ("alloc many: {0}", small_count); }
private void Cleanup(GCHandle[] argStrHandles, GCHandle argPtrsHandle, IntPtr gsInstancePtr) { for (int i = 0; i < argStrHandles.Length; i++) argStrHandles[i].Free(); argPtrsHandle.Free(); ExitAPI(gsInstancePtr); DeleteAPIInstance(gsInstancePtr); }
public IntPtr GetContextHandle() { if ((_selfGCHandle.IsAllocated == false)) { _selfGCHandle = GCHandle.Alloc( this, GCHandleType.Normal); } return GCHandle.ToIntPtr(_selfGCHandle); }
private static void deterministicStaticInit() { __noData = (IntPtr) (-1); __defaultCmdSpace = (IntPtr) (-1); modFlags = ApiGroup.Off; modIdentity = string.Empty; ctrlCallback = new CtrlCB(Bid.SetApiGroupBits); cookieObject = new BindingCookie(); hCookie = GCHandle.Alloc(cookieObject, GCHandleType.Pinned); }
/// <summary> /// Update the view. This method triggers the view to be rendered to the /// underlaying texture. /// </summary> /// <returns>true if the view was actually updated</returns> public bool UpdateView() { if (View != null) { m_DataPin = GCHandle.Alloc(m_Data, System.Runtime.InteropServices.GCHandleType.Pinned); return View.GetAsBitmap(m_DataPin.AddrOfPinnedObject(), Width * Height * 4); } return false; }
// Unity audio callback public void OnAudioFilterRead(float[] data, int channels) { if(dataPtr == IntPtr.Zero) { dataHandle = GCHandle.Alloc(data,GCHandleType.Pinned); dataPtr = dataHandle.AddrOfPinnedObject(); } if (islibpdready) { LibPD.Process(numberOfTicks, dataPtr, dataPtr); } }
void Initialize() { GStreamer.GUBUnityDebugLogPFN log_handler = null; if (Application.isEditor) { log_handler = (int level, string message) => Debug.logger.Log((LogType)level, "GUB", message); } GStreamer.Ref("2", log_handler); m_instanceHandle = GCHandle.Alloc(this); m_Pipeline = new GstUnityBridgePipeline(name + GetInstanceID(), OnFinish, null, null, (System.IntPtr)m_instanceHandle); }
public ChannelTexture(int width, int height, TextureFormat format) { tex = new Texture2D(width, height, format, false); tex.wrapMode = TextureWrapMode.Clamp; //important for NPOT #if !((UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR) pixels = tex.GetPixels32(0); handle = GCHandle.Alloc(pixels, GCHandleType.Pinned); #endif ReAlloc(); }
public static void arwRegisterLogCallback(LogCallback lcb) { if (lcb != null) { logCallback = lcb; logCallbackGCH = GCHandle.Alloc(logCallback); // Does not need to be pinned, see http://stackoverflow.com/a/19866119/316487 } if (Application.platform == RuntimePlatform.IPhonePlayer) ARNativePluginStatic.arwRegisterLogCallback(logCallback); else ARNativePlugin.arwRegisterLogCallback(logCallback); if (lcb == null) { logCallback = null; logCallbackGCH.Free(); } }
void Start() { camera_ = get_camera(); if (camera_ == IntPtr.Zero) { Debug.LogError("camera cannot be opened."); return; } texture_ = new Texture2D(640, 480, TextureFormat.RGBA32, false); pixels_ = texture_.GetPixels32(); handle_ = GCHandle.Alloc(pixels_, GCHandleType.Pinned); ptr_ = handle_.AddrOfPinnedObject(); GetComponent<Renderer>().material.mainTexture = texture_; }
IEnumerator LoadFile() { ms_www = new WWW(m_bankPath); yield return ms_www; uint in_uInMemoryBankSize = 0; // Allocate an aligned buffer try { ms_pinnedArray = GCHandle.Alloc(ms_www.bytes, GCHandleType.Pinned); ms_pInMemoryBankPtr = ms_pinnedArray.AddrOfPinnedObject(); in_uInMemoryBankSize = (uint)ms_www.bytes.Length; // Array inside the WWW object is not aligned. Allocate a new array for which we can guarantee the alignment. if( (ms_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0 ) { byte[] alignedBytes = new byte[ms_www.bytes.Length + AK_BANK_PLATFORM_DATA_ALIGNMENT]; GCHandle new_pinnedArray = GCHandle.Alloc(alignedBytes, GCHandleType.Pinned); IntPtr new_pInMemoryBankPtr = new_pinnedArray.AddrOfPinnedObject(); int alignedOffset = 0; // New array is not aligned, so we will need to use an offset inside it to align our data. if( (new_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0 ) { Int64 alignedPtr = (new_pInMemoryBankPtr.ToInt64() + AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) & ~AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK; alignedOffset = (int)(alignedPtr - new_pInMemoryBankPtr.ToInt64()); new_pInMemoryBankPtr = new IntPtr(alignedPtr); } // Copy the bank's bytes in our new array, at the correct aligned offset. Array.Copy (ms_www.bytes, 0, alignedBytes, alignedOffset, ms_www.bytes.Length); ms_pInMemoryBankPtr = new_pInMemoryBankPtr; ms_pinnedArray.Free(); ms_pinnedArray = new_pinnedArray; } } catch { yield break; } AKRESULT result = AkSoundEngine.LoadBank(ms_pInMemoryBankPtr, in_uInMemoryBankSize, out ms_bankID); if( result != AKRESULT.AK_Success ) { Debug.LogError ("AkMemBankLoader: bank loading failed with result " + result.ToString ()); } }
void OnEnable() { Debug.Log("SampleRate: " + AudioSettings.outputSampleRate); Debug.Log("Speaker: " + AudioSettings.speakerMode.ToString()); int bufferLength = 0; int numBuffers = 0; AudioSettings.GetDSPBufferSize(out bufferLength, out numBuffers); Debug.Log("DSP using " + numBuffers + " buffers of " + bufferLength + " bytes"); _buffer = new float[bufferLength*256]; _bufferIndex = 0; Debug.Log("Buffer size: " + _buffer.Length); _bufferHandle = GCHandle.Alloc(_buffer, GCHandleType.Pinned); }
public request(int alloc_volume, float surv_fraction) { survivors = new Object[1 + (int)(alloc_volume * surv_fraction) / 1000]; int i = 0; int volume = 0; //allocate half of the request size. while (volume < alloc_volume / 2) { int alloc_surv = r.Next(1000, 2000 + 2 * i); int alloc = (int)(alloc_surv / surv_fraction) - alloc_surv; int j = 0; while (j < alloc) { int s = r.Next(100, 200 + 2 * j); Object x = new byte[s]; j += s; } survivors[i] = new byte[alloc_surv]; i++; volume += alloc_surv + alloc; } //allocate one pinned buffer pin = GCHandle.Alloc (new byte [100], GCHandleType.Pinned); //allocate the rest of the request while (volume < alloc_volume) { int alloc_surv = r.Next(1000, 2000 + 2 * i); int alloc = (int)(alloc_surv / surv_fraction) - alloc_surv; int j = 0; while (j < alloc) { int s = r.Next(100, 200 + 2 * j); Object x = new byte[s]; j += s; } survivors[i] = new byte[alloc_surv]; i++; volume += alloc_surv + alloc; } }
// Update is called once per frame void Update () { // 投影 if (projection_flag) { // off-screen rendering //var camtex = RenderTexture.GetTemporary(proWidth, proHeight, 24, RenderTextureFormat.Default, RenderTextureReadWrite.Default, 1); //myProjector.targetTexture = camtex; //myProjector.Render(); //RenderTexture.active = camtex; //tex.ReadPixels(new Rect(0, 0, camtex.width, camtex.height), 0, 0); //tex.Apply(); RenderTexture.active = ProjectorImage; tex.ReadPixels(new Rect(0, 0, ProjectorImage.width, ProjectorImage.height), 0, 0); tex.Apply(); // Convert texture to ptr texturePixels_ = tex.GetPixels32(); texturePixelsHandle_ = GCHandle.Alloc(texturePixels_, GCHandleType.Pinned); texturePixelsPtr_ = texturePixelsHandle_.AddrOfPinnedObject(); //投影するとゆがむので、(逆方向に)歪ませる undistort(texturePixelsPtr_, texturePixelsPtr_, proWidth, proHeight, procamManager.proj_K, procamManager.proj_dist); // Show a window fullWindow(windowName, displayNum, texturePixelsPtr_, proWidth, proHeight); //drawTextureFullWindow(window_, texturePixelsPtr_); texturePixelsHandle_.Free(); //影画像のレンダリング Graphics.Blit(ProjectorImage, shadowImage, shadowMat); //RenderTexture.active = null; //RenderTexture.ReleaseTemporary(camtex); //myProjector.targetTexture = null; RenderTexture.active = null; } }
public static int Main() { // The third element needs to be updated if Pinned is no longer the last value in the GCHandleType enum long[] invalidValues = { Int32.MinValue, -1, (long)(GCHandleType.Pinned + 1), Int32.MaxValue, UInt32.MaxValue, Int64.MaxValue }; bool passed = true; for (int i = 0; i < invalidValues.Length; i++) { // GCHandle.Alloc internally casts the GCHandleType to a uint Console.WriteLine("Input: {0}, Converted to: {1}", invalidValues[i], (uint)invalidValues[i]); GCHandle gch = new GCHandle(); try { gch = GCHandle.Alloc(new object(), (GCHandleType)(invalidValues[i])); Console.WriteLine("Failed"); passed = false; gch.Free(); } catch (ArgumentOutOfRangeException) { // caught the expected exception Console.WriteLine("Passed"); } catch (Exception e) { Console.WriteLine("Caught unexpected exception"); Console.WriteLine(e); passed = false; } Console.WriteLine(); } if (passed) { Console.WriteLine("Test Passed"); return 100; } Console.WriteLine("Test Failed"); return 1; }
public static int Main() { int NUM = 2500; int[][] arr = new int[NUM][]; GCHandle[] handle = new GCHandle[NUM]; IntPtr[] oldaddr = new IntPtr[NUM]; for (int i = 0; i < NUM; i++) { arr[i] = new int[NUM]; handle[i] = GCUtil.Alloc(arr[i], GCHandleType.Pinned); oldaddr[i] = GCUtil.AddrOfPinnedObject(handle[i]); } GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < NUM; i++) { if (GCUtil.AddrOfPinnedObject(handle[i]) != oldaddr[i]) { Console.WriteLine("Test failed!"); return 1; } } GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < NUM; i++) { if (handle[i].IsAllocated != true) { Console.WriteLine("Test failed!"); return 1; } } Console.WriteLine("Test passed!"); return 100; }
// We distinguish between permanent and mid so we can free Mid and // influence the demotion effect. If Mid is a lot, we will hit // demotion; otherwise they will make into gen2. public MyRequest(int sizePermanent, int sizeMid, bool pinned) { if ((s_count % 32) == 0) { sizePermanent = 1; sizeMid = 1; } mObj = new MidObj[sizeMid]; mObj[0] = new MidObj(s_count, this); obj = new byte[sizePermanent]; FillInPin(obj); _is_pinned = pinned; if (pinned) { pin = GCHandle.Alloc(obj, GCHandleType.Pinned); } s_count++; }
public static void Main() { int NUM = 2500; int[][] arr = new int[NUM][]; GCHandle[] handle = new GCHandle[NUM]; IntPtr[] oldaddr = new IntPtr[NUM]; for(int i=0;i<NUM;i++) { arr[i] = new int[NUM]; handle[i] = GCHandle.Alloc(arr[i],GCHandleType.Pinned); oldaddr[i] = handle[i].AddrOfPinnedObject(); } GC.Collect(); GC.WaitForPendingFinalizers(); for(int i=0;i<NUM;i++) { if(handle[i].AddrOfPinnedObject() != oldaddr[i]) { Environment.ExitCode=1; Console.WriteLine("Test failed!"); return; } } GC.Collect(); GC.WaitForPendingFinalizers(); for(int i=0;i<NUM;i++) { if(handle[i].IsAllocated != true) { Environment.ExitCode=1; Console.WriteLine("Test failed!"); return; } } Environment.ExitCode=0; Console.WriteLine("Test passed!"); }
void Start() { // テクスチャを生成 texture_ = new Texture2D(10, 10, TextureFormat.RGB24, false); // テクスチャの拡大方法をニアレストネイバーに変更 texture_.filterMode = FilterMode.Point; // Color32 型の配列としてテクスチャの参照をもらう pixels_ = texture_.GetPixels32(); // GC されないようにする pixels_handle_ = GCHandle.Alloc(pixels_, GCHandleType.Pinned); // そのテクスチャのアドレスをもらう pixels_ptr_ = pixels_handle_.AddrOfPinnedObject(); // スクリプトがアタッチされたオブジェクトのテクスチャをコレにする GetComponent<Renderer>().material.mainTexture = texture_; // ネイティブ側でテクスチャを生成 create_check_texture(pixels_ptr_, texture_.width, texture_.height, 4); // セットして反映させる texture_.SetPixels32(pixels_); texture_.Apply(false, true); // GC 対象にする pixels_handle_.Free(); }
public void H5RcreateTest2() { byte[] path = Encoding.UTF8.GetBytes(String.Join("/", m_utf8strings)); // make room for the trailling \0 byte[] name = new byte[path.Length + 1]; Array.Copy(path, name, path.Length); Assert.IsTrue( H5G.close(H5G.create(m_v2_test_file, path, m_lcpl_utf8)) >= 0); byte[] refer = new byte[H5R.OBJ_REF_BUF_SIZE]; GCHandle hnd = GCHandle.Alloc(refer, GCHandleType.Pinned); Assert.IsTrue( H5R.create(hnd.AddrOfPinnedObject(), m_v2_test_file, name, H5R.type_t.OBJECT, -1) >= 0); ssize_t size = H5R.get_name(m_v2_test_file, H5R.type_t.OBJECT, hnd.AddrOfPinnedObject(), (byte[])null, IntPtr.Zero); Assert.IsTrue(size.ToInt32() == name.Length); byte[] buf = new byte[size.ToInt32() + 1]; size = H5R.get_name(m_v2_test_file, H5R.type_t.OBJECT, hnd.AddrOfPinnedObject(), buf, new IntPtr(buf.Length)); Assert.IsTrue(size.ToInt32() == name.Length); hnd.Free(); // we need to account for the leading "/", which was not included // in path for (int i = 0; i < name.Length; ++i) { Assert.IsTrue(name[i] == buf[i + 1]); } }
/// <summary> /// Creates a new Promise with the given callback. /// /// Currently, creating a promise directly uses the Main Loop scheduler the source of notifications (i.e. the /// future callbacks will be called mainly from a loop iteration). /// </summary> public Promise(CancelCb cancelCb = null) { Efl.Loop loop = Efl.App.AppMain; // Should we be able to pass different schedulers? IntPtr scheduler = efl_loop_future_scheduler_get(loop.NativeHandle); IntPtr cb_data = IntPtr.Zero; // A safety clean callback to mark this wrapper as invalid CancelCb safetyCb = () => { Handle = IntPtr.Zero; if (cancelCb != null) { cancelCb(); } }; CleanupHandle = GCHandle.Alloc(safetyCb); cb_data = GCHandle.ToIntPtr(CleanupHandle); this.Handle = eina_promise_new(scheduler, NativeCancelCb, cb_data); }
private static void ReadElements(MemoryMappedFile mmf, _HWiNFO_SHARED_MEM hWiNFOMemory) { for (uint index = 0; index < hWiNFOMemory.NumReadingElements; ++index) { using (var viewStream = mmf.CreateViewStream(hWiNFOMemory.OffsetOfReadingSection + index * hWiNFOMemory.SizeOfReadingElement, hWiNFOMemory.SizeOfReadingElement, MemoryMappedFileAccess.Read)) { var buffer = new byte[(int)hWiNFOMemory.SizeOfReadingElement]; viewStream.Read(buffer, 0, (int)hWiNFOMemory.SizeOfReadingElement); var gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); var structure = (_HWiNFO_ELEMENT)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(_HWiNFO_ELEMENT)); gcHandle.Free(); var sensor = FullSensorData[(int) structure.SensorIndex]; var elementKey = sensor.SensorId + "-" + sensor.SensorInstance + "-" + structure.ElementId; var element = new ElementObj { ElementKey = elementKey, SensorType = structure.SensorType, ElementId = structure.ElementId, LabelOrig = structure.LabelOrig, LabelUser = structure.LabelUser, Unit = structure.Unit, NumericValue = (float)structure.Value, Value = NumberFormat(structure.SensorType, structure.Unit, structure.Value), ValueMin = NumberFormat(structure.SensorType, structure.Unit, structure.ValueMin), ValueMax = NumberFormat(structure.SensorType, structure.Unit, structure.ValueMax), ValueAvg = NumberFormat(structure.SensorType, structure.Unit,structure.ValueAvg) }; sensor.Elements[elementKey] = element; } } }
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf <Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf <Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf <Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef <byte>(inArray1Ptr), ref Unsafe.As <Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef <byte>(inArray2Ptr), ref Unsafe.As <Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); }
private static NativeMethods.REQUEST_NOTIFICATION_STATUS OnAsyncCompletion(IntPtr pvManagedHttpContext, int hr, int bytes) { IISHttpContext?context = null; try { context = (IISHttpContext?)GCHandle.FromIntPtr(pvManagedHttpContext).Target; // Context can be null if ungraceful shutdown. if (context == null) { return(NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST); } context.OnAsyncCompletion(hr, bytes); return(NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_PENDING); } catch (Exception ex) { context?.Server._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(OnAsyncCompletion)}."); return(NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST); } }
public static async Task<Mat> FromStorageFile(StorageFile file) { using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); Size s = new Size((int)decoder.PixelWidth, (int)decoder.PixelHeight); BitmapTransform transform = new BitmapTransform(); PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); byte[] sourcePixels = pixelData.DetachPixelData(); GCHandle handle = GCHandle.Alloc(sourcePixels, GCHandleType.Pinned); using (Image<Bgra, Byte> img = new Image<Bgra, byte>(s.Width, s.Height, s.Width * 4, handle.AddrOfPinnedObject())) { Mat m = new Mat(); CvInvoke.CvtColor(img, m, ColorConversion.Bgra2Bgr); handle.Free(); return m; } } }
public unsafe void GcHandleTest() { #if !DEBUG var count = 100_000_000; #else var count = 1_000; #endif var bytes = new byte[10000]; // if we work with Memory abstraction GCHandle is no-go // either move to off-heap or pre-pin, handle is 19MOPS, slower than RMP // fixed is OK with 250+ MOPS in this test using (Benchmark.Run("GCHandle", count)) { for (int i = 0; i < count; i++) { var h = GCHandle.Alloc(bytes, GCHandleType.Pinned); h.Free(); } } var sum = 0.0; using (Benchmark.Run("Fixed", count)) { for (int i = 0; i < count; i++) { fixed(byte *ptr = &bytes[0]) { sum += *ptr; } } } Console.WriteLine(sum); }
private IntPtr OutputFileOpen(NativeMethods.FdiNotification fdin) { try { var extractFile = new ArchiveFile { Name = GetFileName(fdin) }; if (ShouldIgnoreFile(extractFile)) { //ignore this file. return(IntPtr.Zero); } var stream = new MemoryStream(); GCHandle gch = GCHandle.Alloc(stream); extractFile.Handle = (IntPtr)gch; AddToListOfFiles(extractFile); } catch (Exception ex) { SbaLogger.Instance.Verbose(ex); } //return IntPtr.Zero so that the iteration will keep on going return(IntPtr.Zero); }
internal void InitTarget(IDebugDraw target) { _drawAabb = new DrawAabbUnmanagedDelegate(target.DrawAabb); _drawArc = new DrawArcUnmanagedDelegate(target.DrawArc); _drawBox = new DrawBoxUnmanagedDelegate(target.DrawBox); _drawCapsule = new DrawCapsuleUnmanagedDelegate(target.DrawCapsule); _drawCone = new DrawConeUnmanagedDelegate(target.DrawCone); _drawContactPoint = new DrawContactPointUnmanagedDelegate(target.DrawContactPoint); _drawCylinder = new DrawCylinderUnmanagedDelegate(target.DrawCylinder); _drawLine = new DrawLineUnmanagedDelegate(target.DrawLine); _drawPlane = new DrawPlaneUnmanagedDelegate(target.DrawPlane); _drawSphere = new DrawSphereUnmanagedDelegate(target.DrawSphere); _drawSpherePatch = new DrawSpherePatchUnmanagedDelegate(target.DrawSpherePatch); _drawTransform = new DrawTransformUnmanagedDelegate(target.DrawTransform); _drawTriangle = new DrawTriangleUnmanagedDelegate(target.DrawTriangle); _getDebugMode = new GetDebugModeUnmanagedDelegate(GetDebugModeUnmanaged); _cb = new SimpleCallback(SimpleCallbackUnmanaged); _native = btIDebugDrawWrapper_new( GCHandle.ToIntPtr(GCHandle.Alloc(this)), Marshal.GetFunctionPointerForDelegate(_drawAabb), Marshal.GetFunctionPointerForDelegate(_drawArc), Marshal.GetFunctionPointerForDelegate(_drawBox), Marshal.GetFunctionPointerForDelegate(_drawCapsule), Marshal.GetFunctionPointerForDelegate(_drawCone), Marshal.GetFunctionPointerForDelegate(_drawContactPoint), Marshal.GetFunctionPointerForDelegate(_drawCylinder), Marshal.GetFunctionPointerForDelegate(_drawLine), Marshal.GetFunctionPointerForDelegate(_drawPlane), Marshal.GetFunctionPointerForDelegate(_drawSphere), Marshal.GetFunctionPointerForDelegate(_drawSpherePatch), Marshal.GetFunctionPointerForDelegate(_drawTransform), Marshal.GetFunctionPointerForDelegate(_drawTriangle), Marshal.GetFunctionPointerForDelegate(_getDebugMode), Marshal.GetFunctionPointerForDelegate(_cb)); }
private void ReadBytes(Array array, Int32 arrayOffset, Int32 arraySize, Int32 countOffset) { if (arraySize < arrayOffset + countOffset) { throw new ArgumentException(Resources.Array_out_of_bounds); } if (Stream.Length < Stream.Position + countOffset) { throw new ArgumentException(Resources.Stream_out_of_bounds); } GCHandle arrayHandle = GCHandle.Alloc(array, GCHandleType.Pinned); unsafe { IntPtr arrayPtr = new IntPtr((Byte *)(arrayHandle.AddrOfPinnedObject().ToPointer()) + arrayOffset); try { while (countOffset > 0) { Int32 bytesRead = Stream.Read(buffer, 0, Math.Min(buffer.Length, countOffset)); Marshal.Copy(buffer, 0, arrayPtr, bytesRead); arrayPtr = new IntPtr(((Byte *)(arrayPtr.ToPointer())) + bytesRead); countOffset -= bytesRead; } } finally { arrayHandle.Free(); } } }
/// <summary> /// Helper method to try to get an image in the specified format from the dataObject /// the DIB readed should solve the issue reported here: https://sourceforge.net/projects/greenshot/forums/forum/676083/topic/6354353/index/page/1 /// It also supports Format17/DibV5, by using the following information: http://stackoverflow.com/a/14335591 /// </summary> /// <param name="format">string with the format</param> /// <param name="dataObject">IDataObject</param> /// <returns>Image or null</returns> private static Image GetImageForFormat(string format, IDataObject dataObject) { object clipboardObject = GetFromDataObject(dataObject, format); MemoryStream imageStream = clipboardObject as MemoryStream; if (!isValidStream(imageStream)) { // TODO: add "HTML Format" support here... return(clipboardObject as Image); } else { if (config.EnableSpecialDIBClipboardReader) { if (format == FORMAT_17 || format == DataFormats.Dib) { LOG.Info("Found DIB stream, trying to process it."); try { byte[] dibBuffer = new byte[imageStream.Length]; imageStream.Read(dibBuffer, 0, dibBuffer.Length); BITMAPINFOHEADER infoHeader = BinaryStructHelper.FromByteArray <BITMAPINFOHEADER>(dibBuffer); if (!infoHeader.IsDibV5) { LOG.InfoFormat("Using special DIB <v5 format reader with biCompression {0}", infoHeader.biCompression); int fileHeaderSize = Marshal.SizeOf(typeof(BITMAPFILEHEADER)); uint infoHeaderSize = infoHeader.biSize; int fileSize = (int)(fileHeaderSize + infoHeader.biSize + infoHeader.biSizeImage); BITMAPFILEHEADER fileHeader = new BITMAPFILEHEADER(); fileHeader.bfType = BITMAPFILEHEADER.BM; fileHeader.bfSize = fileSize; fileHeader.bfReserved1 = 0; fileHeader.bfReserved2 = 0; fileHeader.bfOffBits = (int)(fileHeaderSize + infoHeaderSize + infoHeader.biClrUsed * 4); byte[] fileHeaderBytes = BinaryStructHelper.ToByteArray <BITMAPFILEHEADER>(fileHeader); using (MemoryStream bitmapStream = new MemoryStream()) { bitmapStream.Write(fileHeaderBytes, 0, fileHeaderSize); bitmapStream.Write(dibBuffer, 0, dibBuffer.Length); bitmapStream.Seek(0, SeekOrigin.Begin); using (Image tmpImage = Image.FromStream(bitmapStream)) { if (tmpImage != null) { return(ImageHelper.Clone(tmpImage)); } } } } else { LOG.Info("Using special DIBV5 / Format17 format reader"); // CF_DIBV5 IntPtr gcHandle = IntPtr.Zero; try { GCHandle handle = GCHandle.Alloc(dibBuffer, GCHandleType.Pinned); gcHandle = GCHandle.ToIntPtr(handle); return(new Bitmap(infoHeader.biWidth, infoHeader.biHeight, -(int)(infoHeader.biSizeImage / infoHeader.biHeight), infoHeader.biBitCount == 32 ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb, new IntPtr(handle.AddrOfPinnedObject().ToInt32() + infoHeader.OffsetToPixels + (infoHeader.biHeight - 1) * (int)(infoHeader.biSizeImage / infoHeader.biHeight)))); } catch (Exception ex) { LOG.Error("Problem retrieving Format17 from clipboard.", ex); } finally { if (gcHandle == IntPtr.Zero) { GCHandle.FromIntPtr(gcHandle).Free(); } } } } catch (Exception dibEx) { LOG.Error("Problem retrieving DIB from clipboard.", dibEx); } } } else { LOG.Info("Skipping special DIB format reader as it's disabled in the configuration."); } try { imageStream.Seek(0, SeekOrigin.Begin); using (Image tmpImage = Image.FromStream(imageStream, true, true)) { if (tmpImage != null) { LOG.InfoFormat("Got image with clipboard format {0} from the clipboard.", format); return(ImageHelper.Clone(tmpImage)); } } } catch (Exception streamImageEx) { LOG.Error(string.Format("Problem retrieving {0} from clipboard.", format), streamImageEx); } } return(null); }
public static IntPtr ToIntPtr(this GCHandle target) { return(GCHandle.ToIntPtr(target)); }
public static IntPtr ToIntPtr(this object target) { return(GCHandle.Alloc(target).ToIntPtr()); }
public static void Reload(IntPtr data, IntPtr rm, ref double maxValue) { Measure measure = (Measure)GCHandle.FromIntPtr(data).Target; measure.Reload(new Rainmeter.API(rm), ref maxValue); }
public static GCHandle ToGcHandle(this object target) { return(GCHandle.Alloc(target)); }
public void Pump() { EventType eventType; while ((eventType = (EventType)NextEventType(_peerIndex)) != EventType.None) { switch (eventType) { case EventType.Initialized: { PopInitializedEvent(_peerIndex); if (OnOpen != null) { OnOpen(); } break; } case EventType.Connected: { var size = PeekReceivedEventSize(_peerIndex); var buffer = new byte[size]; var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); var connIndex = PopConnectedEvent(_peerIndex, pinnedBuffer.AddrOfPinnedObject(), size); pinnedBuffer.Free(); var remoteId = Encoding.UTF8.GetString(buffer); _connections[connIndex] = new Connection(this, connIndex, remoteId); Debug.Log(string.Format("Connected, index: {0}, buffer len: {1}, id: \"{2}\", id len {3}", connIndex, buffer.Length, remoteId, remoteId.Length)); if (OnConnection != null) { OnConnection(_connections[connIndex]); } break; } case EventType.Received: { var size = PeekReceivedEventSize(_peerIndex); var buffer = new byte[size]; var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); var connIndex = PopReceivedEvent(_peerIndex, pinnedBuffer.AddrOfPinnedObject(), size); var str = Encoding.UTF8.GetString(buffer); pinnedBuffer.Free(); Debug.Log(string.Format("Received, index: {0}, buffer len: {1}, str: \"{2}\", str len {3}", connIndex, buffer.Length, str, str.Length)); _connections[connIndex].EmitOnData(str); break; } case EventType.ConnClosed: { var connIndex = PopConnClosedEvent(_peerIndex); _connections[connIndex].EmitOnClose(); break; } case EventType.PeerDisconnected: { PopPeerDisconnectedEvent(_peerIndex); if (OnDisconnected != null) { OnDisconnected(); } break; } case EventType.PeerClosed: { PopPeerClosedEvent(_peerIndex); if (OnClose != null) { OnClose(); } break; } case EventType.Error: { var buffer = new byte[256]; var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); PopErrorEvent(_peerIndex, pinnedBuffer.AddrOfPinnedObject(), buffer.Length); pinnedBuffer.Free(); if (OnError != null) { OnError(DecodeUtf16Z(buffer)); } break; } default: { PopAnyEvent(_peerIndex); break; } } } }
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions) { SafeSslHandle context = null; // Always use SSLv23_method, regardless of protocols. It supports negotiating to the highest // mutually supported version and can thus handle any of the set protocols, and we then use // SetProtocolOptions to ensure we only allow the ones requested. using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method)) { if (innerContext.IsInvalid) { throw CreateSslException(SR.net_allocate_ssl_context_failed); } // Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just // create the handle, it's rooted by the using, no one else has a reference to it, etc. Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols); // The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet // shutdown (we aren't negotiating for session close to enable later session // restoration). // // If you find yourself wanting to remove this line to enable bidirectional // close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect(). // https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html Ssl.SslCtxSetQuietShutdown(innerContext); if (!Ssl.SetEncryptionPolicy(innerContext, policy)) { throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } bool hasCertificateAndKey = certHandle != null && !certHandle.IsInvalid && certKeyHandle != null && !certKeyHandle.IsInvalid; if (hasCertificateAndKey) { SetSslCertificate(innerContext, certHandle, certKeyHandle); } if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired) { Ssl.SslCtxSetVerify(innerContext, s_verifyClientCertificate); } GCHandle alpnHandle = default; try { if (sslAuthenticationOptions.ApplicationProtocols != null) { if (sslAuthenticationOptions.IsServer) { alpnHandle = GCHandle.Alloc(sslAuthenticationOptions.ApplicationProtocols); Interop.Ssl.SslCtxSetAlpnSelectCb(innerContext, s_alpnServerCallback, GCHandle.ToIntPtr(alpnHandle)); } else { if (Interop.Ssl.SslCtxSetAlpnProtos(innerContext, sslAuthenticationOptions.ApplicationProtocols) != 0) { throw CreateSslException(SR.net_alpn_config_failed); } } } context = SafeSslHandle.Create(innerContext, sslAuthenticationOptions.IsServer); Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create"); if (context.IsInvalid) { context.Dispose(); throw CreateSslException(SR.net_allocate_ssl_context_failed); } if (!sslAuthenticationOptions.IsServer) { // The IdnMapping converts unicode input into the IDNA punycode sequence. string punyCode = s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost); // Similar to windows behavior, set SNI on openssl by default for client context, ignore errors. Ssl.SslSetTlsExtHostName(context, punyCode); } if (hasCertificateAndKey) { bool hasCertReference = false; try { certHandle.DangerousAddRef(ref hasCertReference); using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle())) { using (X509Chain chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false)) { if (chain != null && !Ssl.AddExtraChainCertificates(context, chain)) { throw CreateSslException(SR.net_ssl_use_cert_failed); } } } } finally { if (hasCertReference) { certHandle.DangerousRelease(); } } } context.AlpnHandle = alpnHandle; } catch { if (alpnHandle.IsAllocated) { alpnHandle.Free(); } throw; } } return(context); }
public static double Update(IntPtr data) { Measure measure = (Measure)GCHandle.FromIntPtr(data).Target; return(measure.Update()); }
private static NativeExpressAdClient IntPtrToNativeExpressAdClient(IntPtr nativeExpressAdClient) { GCHandle handle = (GCHandle)nativeExpressAdClient; return(handle.Target as NativeExpressAdClient); }
public static bool Compare(GCHandle?val, GCHandle val1) { return(Compare(val.Value, val1)); }
private void btn_Open_Click(object sender, EventArgs e) { Int32 status = VirtualFG40Library.MCAM_ERR_SUCCESS; UInt32 camNum = 0; try { // Update Device List status = _virtualFG40.UpdateDevice(); if (status != VirtualFG40Library.MCAM_ERR_SUCCESS) { _virtualFG40.FreeSystem(); throw new Exception(String.Format("Update Device list failed : {0}", status)); } status = _virtualFG40.GetAvailableCameraNum(ref camNum); if (camNum <= 0) { _virtualFG40.FreeSystem(); throw new Exception("The camera can not be connected."); } // camera open status = _virtualFG40.OpenDevice(0, ref _hDevice); if (status != VirtualFG40Library.MCAM_ERR_SUCCESS) { _virtualFG40.FreeSystem(); throw new Exception(String.Format("Open device failed : {0}", status)); } _isOpen = true; // Call Set Feature SetFeature(); // Get Width status = _virtualFG40.GetIntReg(_hDevice, VirtualFG40Library.MCAM_WIDTH, ref _width); if (status != VirtualFG40Library.MCAM_ERR_SUCCESS) { throw new Exception(String.Format("Read Register failed : {0}", status)); } // Get Height status = _virtualFG40.GetIntReg(_hDevice, VirtualFG40Library.MCAM_HEIGHT, ref _height); if (status != VirtualFG40Library.MCAM_ERR_SUCCESS) { throw new Exception(String.Format("Read Register failed : {0}", status)); } // Crevis Callback Function VirtualFG40Library.CallbackFunc vfgCallback = new VirtualFG40Library.CallbackFunc(OnCallback); _virtualFG40.SetCallbackFunction(_hDevice, VirtualFG40Library.EVENT_NEW_IMAGE, vfgCallback, _userdata); _gch = GCHandle.Alloc(vfgCallback); pictureBox_Display.Image = new Bitmap(_width, _height, PixelFormat.Format8bppIndexed); } catch (Exception ex) { MessageBox.Show(ex.Message); } btn_Open.Enabled = false; btn_Close.Enabled = true; btn_Grab.Enabled = true; btn_Play.Enabled = true; btn_Stop.Enabled = true; }
public static bool Compare(GCHandle val, GCHandle val1) { return(val == val1); }
public static GCHandle Create(GCHandle val) { return(GCHANDLE); }
static Helper() { GCHANDLE = GCHandle.Alloc(System.Console.Out); }
public PinnedBitmap(int width, int height) { Data = new int[width * height]; handle = GCHandle.Alloc(Data, GCHandleType.Pinned); Bitmap = new Bitmap(width, height, width * 4, PixelFormat.Format32bppArgb, handle.AddrOfPinnedObject()); }
public static void AddPinnedObject(int objSize) { gcHandleArr.Add(GCHandle.Alloc(CreateObject(objSize, true), GCHandleType.Pinned)); }
public void Recognize(Mat m) { int[] dim = new int[] { 1, m.Height, m.Width, 3 }; if (_imageTensor == null) { _imageTensor = new Tensor(Emgu.TF.DataType.Uint8, dim); } else { if (!(_imageTensor.Type == Emgu.TF.DataType.Uint8 && Enumerable.SequenceEqual(dim, _imageTensor.Dim))) { _imageTensor.Dispose(); _imageTensor = new Tensor(Emgu.TF.DataType.Uint8, dim); } } Emgu.TF.TensorConvert.ReadTensorFromMatBgr(m, _imageTensor); MaskRcnnInceptionV2Coco.RecognitionResult[] results; if (_coldSession) { //First run of the recognition graph, here we will compile the graph and initialize the session //This is expected to take much longer time than consecutive runs. results = _inceptionGraph.Recognize(_imageTensor)[0]; _coldSession = false; } //Here we are trying to time the execution of the graph after it is loaded Stopwatch sw = Stopwatch.StartNew(); results = _inceptionGraph.Recognize(_imageTensor)[0]; sw.Stop(); int goodResultCount = 0; foreach (var r in results) { if (r.Probability > 0.5) { float x1 = r.Region[0] * m.Height; float y1 = r.Region[1] * m.Width; float x2 = r.Region[2] * m.Height; float y2 = r.Region[3] * m.Width; RectangleF rectf = new RectangleF(y1, x1, y2 - y1, x2 - x1); Rectangle rect = Rectangle.Round(rectf); rect.Intersect(new Rectangle(Point.Empty, m.Size)); //only keep the region that is inside the image if (rect.IsEmpty) { continue; } //draw the rectangle around the region CvInvoke.Rectangle(m, rect, new Emgu.CV.Structure.MCvScalar(0, 0, 255), 2); #region draw the mask float[,] mask = r.Mask; GCHandle handle = GCHandle.Alloc(mask, GCHandleType.Pinned); using (Mat mk = new Mat(new Size(mask.GetLength(1), mask.GetLength(0)), Emgu.CV.CvEnum.DepthType.Cv32F, 1, handle.AddrOfPinnedObject(), mask.GetLength(1) * sizeof(float))) using (Mat subRegion = new Mat(m, rect)) using (Mat maskLarge = new Mat()) using (Mat maskLargeInv = new Mat()) using (Mat largeColor = new Mat(subRegion.Size, Emgu.CV.CvEnum.DepthType.Cv8U, 3)) { CvInvoke.Resize(mk, maskLarge, subRegion.Size); //give the mask at least 30% transparency using (ScalarArray sa = new ScalarArray(0.7)) CvInvoke.Min(sa, maskLarge, maskLarge); //Create the inverse mask for the original image using (ScalarArray sa = new ScalarArray(1.0)) CvInvoke.Subtract(sa, maskLarge, maskLargeInv); //The mask color largeColor.SetTo(new Emgu.CV.Structure.MCvScalar(255, 0, 0)); CvInvoke.BlendLinear(largeColor, subRegion, maskLarge, maskLargeInv, subRegion); } handle.Free(); #endregion //draw the label CvInvoke.PutText(m, r.Label, Point.Round(rect.Location), Emgu.CV.CvEnum.FontFace.HersheyComplex, 1.0, new Emgu.CV.Structure.MCvScalar(0, 255, 0), 1); goodResultCount++; } } String resStr = String.Format("{0} objects detected in {1} milliseconds.", goodResultCount, sw.ElapsedMilliseconds); if (_renderMat == null) { _renderMat = new Mat(); } m.CopyTo(_renderMat); //Bitmap bmp = _renderMat.ToBitmap(); if (InvokeRequired) { this.Invoke((MethodInvoker)(() => { messageLabel.Text = resStr; pictureBox.Image = _renderMat; })); } else { messageLabel.Text = resStr; pictureBox.Image = _renderMat; } }
// End DBCs public SpellDifficulty(MainWindow window, MySQL.MySQL mySQLConn) { main = window; mySQL = mySQLConn; for (UInt32 i = 0; i < header.RecordCount; ++i) { body.records[i].ID = new UInt32(); body.records[i].Difficulties = new UInt32[4]; } if (!File.Exists("DBC/SpellDifficulty.dbc")) { main.HandleErrorMessage("SpellDifficulty.dbc was not found!"); return; } FileStream fileStream = new FileStream("DBC/SpellDifficulty.dbc", FileMode.Open); int count = Marshal.SizeOf(typeof(DBC_Header)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); header = (DBC_Header)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(DBC_Header)); handle.Free(); body.records = new SpellDifficulty_DBC_Record[header.RecordCount]; for (UInt32 i = 0; i < header.RecordCount; ++i) { count = Marshal.SizeOf(typeof(SpellDifficulty_DBC_Record)); readBuffer = new byte[count]; reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); body.records[i] = (SpellDifficulty_DBC_Record)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(SpellDifficulty_DBC_Record)); handle.Free(); } reader.Close(); fileStream.Close(); body.lookup = new List <SpellDifficultyLookup>(); int boxIndex = 1; main.Difficulty.Items.Add(0); SpellDifficultyLookup t; t.ID = 0; t.comboBoxIndex = 0; body.lookup.Add(t); for (UInt32 i = 0; i < header.RecordCount; ++i) { int id = (int)body.records[i].ID; SpellDifficultyLookup temp; temp.ID = id; temp.comboBoxIndex = boxIndex; main.Difficulty.Items.Add(id); body.lookup.Add(temp); boxIndex++; } }
internal DisposableHandle(IntPtr ptr, GCHandle handle) { _ptr = ptr; _handle = handle; }
public static void ExecuteBang(IntPtr data, IntPtr args) { Measure measure = (Measure)GCHandle.FromIntPtr(data).Target; measure.ExecuteBang(Marshal.PtrToStringUni(args)); }