public static void FreeString(ref GCHandle handle) { if (handle == NullHandle) return; handle.Free(); }
public void Execute() { // Create GS Instance (GS-API) gsapi_new_instance(out _gsInstancePtr, IntPtr.Zero); // Build Argument Arrays _gsArgStrHandles = new GCHandle[_gsParams.Count]; _gsArgPtrs = new IntPtr[_gsParams.Count]; // Populate Argument Arrays for (int i = 0; i < _gsParams.Count; i++) { _gsArgStrHandles[i] = GCHandle.Alloc(System.Text.ASCIIEncoding.ASCII.GetBytes(_gsParams[i].ToString()), GCHandleType.Pinned); _gsArgPtrs[i] = _gsArgStrHandles[i].AddrOfPinnedObject(); } // Allocate memory that is protected from Garbage Collection _gsArgPtrsHandle = GCHandle.Alloc(_gsArgPtrs, GCHandleType.Pinned); // Init args with GS instance (GS-API) gsapi_init_with_args(_gsInstancePtr, _gsArgStrHandles.Length, _gsArgPtrsHandle.AddrOfPinnedObject()); // Free unmanaged memory for (int i = 0; i < _gsArgStrHandles.Length; i++) _gsArgStrHandles[i].Free(); _gsArgPtrsHandle.Free(); // Exit the api (GS-API) gsapi_exit(_gsInstancePtr); // Delete GS Instance (GS-API) gsapi_delete_instance(_gsInstancePtr); }
static void Main(string[] args) { Console.Write("Enter Passphrase: "); using (var passphrase = GetPassphraseFromConsole()) { Console.WriteLine("Your password:"******"Exception thrown."); } Marshal.ZeroFreeBSTR(ptr); for (var ii = 0; ii < arPass.Length; ii++) { arPass[ii] = '\0'; } handle.Free(); }, null ); } } }
public static System.Drawing.Bitmap ToBitmap(System.Drawing.Icon icon, Skybound.Drawing.Design.IconFormat iconFormat) { Skybound.Drawing.Design.IconFile.BITMAP bitmap; Skybound.Drawing.Design.IconFile.ICONINFO iconinfo; System.Drawing.Bitmap bitmap1 = null; if (icon != null) { if (iconFormat.ColorDepth == System.Windows.Forms.ColorDepth.Depth32Bit) { Skybound.Drawing.Design.IconFile.GetIconInfo(icon.Handle, out iconinfo); bitmap = new Skybound.Drawing.Design.IconFile.BITMAP(); Skybound.Drawing.Design.IconFile.GetObjectBitmap(iconinfo.hbmColor, System.Runtime.InteropServices.Marshal.SizeOf(typeof(Skybound.Drawing.Design.IconFile.BITMAP)), ref bitmap); int i = bitmap.bmWidthBytes * bitmap.bmHeight; int[] iArr = new int[(i / 4)]; Skybound.Drawing.Design.IconFile.GetBitmapBits(iconinfo.hbmColor, i, iArr); System.Runtime.InteropServices.GCHandle gchandle = System.Runtime.InteropServices.GCHandle.Alloc(iArr, System.Runtime.InteropServices.GCHandleType.Pinned); System.Drawing.Bitmap bitmap2 = new System.Drawing.Bitmap(bitmap.bmWidth, bitmap.bmHeight, bitmap.bmWidthBytes, System.Drawing.Imaging.PixelFormat.Format32bppArgb, System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(iArr, 0)); bitmap1 = new System.Drawing.Bitmap(bitmap2.Width, bitmap2.Height); using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap1)) { graphics.DrawImage(bitmap2, 0, 0, bitmap2.Width, bitmap2.Height); } gchandle.Free(); Skybound.Drawing.Design.IconFile.DeleteObject(iconinfo.hbmMask); Skybound.Drawing.Design.IconFile.DeleteObject(iconinfo.hbmColor); } else { bitmap1 = icon.ToBitmap(); } } return(bitmap1); }
public static Packet.PacketHeader ByteArrayToNewStuff(byte[] bytes) { System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(bytes, System.Runtime.InteropServices.GCHandleType.Pinned); Packet.PacketHeader stuff = (Packet.PacketHeader)System.Runtime.InteropServices.Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Packet.PacketHeader)); handle.Free(); return(stuff); }
private int Invoke(SOCKET socket) { _recvOverlapped.hEvent = SocketImports.WSACreateEvent(); if (_recvOverlapped.hEvent == IntPtr.Zero) { // dead, close socket? return -1; } _gcWSABuffer = GCHandle.Alloc(_WSABuffer, GCHandleType.Pinned); var lpWSABuffer = (WSABuffer*)_gcWSABuffer.AddrOfPinnedObject(); _gcRecvOverlapped = GCHandle.Alloc(_recvOverlapped, GCHandleType.Pinned); var plRecvOverlapped = (WSAOverlapped*)_gcRecvOverlapped.AddrOfPinnedObject(); int rc = SocketImports.WSARecv(socket, lpWSABuffer, 1, out _bytesTransferred, ref _socketFlags, plRecvOverlapped, IntPtr.Zero); _gcWSABuffer.Free(); _gcRecvOverlapped.Free(); if (rc == SocketImports.SOCKET_ERROR) { int err = SocketImports.WSAGetLastError(); if (SocketImports.WSA_IO_PENDING != err) { Console.WriteLine("WSARecv failed with error: {0}/{1}", rc, err); } } return rc; }
/// <summary> /// 清除記憶體 /// </summary> private void Clear(string sSecretKey) { // For additional security Pin the key. System.Runtime.InteropServices.GCHandle Gch = System.Runtime.InteropServices.GCHandle.Alloc(sSecretKey, System.Runtime.InteropServices.GCHandleType.Pinned); // Remove the Key from memory. ZeroMemory(Gch.AddrOfPinnedObject(), sSecretKey.Length * 2); Gch.Free(); }
/// <summary> /// Command handler for the history commands. /// The standard implementation of a console has a history function implemented when /// the user presses the UP or DOWN key. /// </summary> private void OnHistory(object sender, EventArgs e) { // Get the command to figure out from the ID if we have to get the previous or the // next element in the history. OleMenuCommand command = sender as OleMenuCommand; if (null == command || command.CommandID.Guid != typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID) { return; } string historyEntry = null; if (command.CommandID.ID == (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.UP) { historyEntry = history.PreviousEntry(); } else if (command.CommandID.ID == (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.DOWN) { historyEntry = history.NextEntry(); } if (string.IsNullOrEmpty(historyEntry)) { return; } // There is something to write on the console, so replace the current text in the // input line with the content of the history. lock (textLines) { // The input line starts by definition at the end of the text marker // used to mark the read only region. TextSpan[] span = new TextSpan[1]; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textStream.ReadOnlyMarker.GetCurrentSpan(span)); // Get the last position in the buffer. int lastLine; int lastIndex; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.GetLastLineIndex(out lastLine, out lastIndex)); // Now replace all this text with the text returned by the history. System.Runtime.InteropServices.GCHandle textHandle = GCHandle.Alloc(historyEntry, GCHandleType.Pinned); try { Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.ReplaceLines(span[0].iEndLine, span[0].iEndIndex, lastLine, lastIndex, textHandle.AddrOfPinnedObject(), historyEntry.Length, null)); } finally { // Free the memory inside the finally block to avoid memory leaks. textHandle.Free(); } } }
public override void Dispose() { if (mWeakHandle.IsAllocated) { SDK_PhyEntity_SetCSharpHandle(CoreObject, IntPtr.Zero); mWeakHandle.Free(); } base.Dispose(); }
public static void DibToFile(Stream stream, string filePath) { // Read the DIB into a Byte array and pin it // This is necessary because some of the unmanaged calls // need a pointer to the Dib bytes. byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); string imagePath = string.Empty; GCHandle gcHandle = new GCHandle(); try { gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); // Reset the stream position since it was read into the byte array // Get the bitmapInfoHeader so we can do some calculations stream.Position = 0; BITMAPINFOHEADER bmpInfoHeader = GetBitMapInfoHeader(stream); if ((bmpInfoHeader.biClrUsed == 0) && (bmpInfoHeader.biBitCount < 16)) bmpInfoHeader.biClrUsed = 1 << bmpInfoHeader.biBitCount; // Get IntPtrs for the DIB itself as well as for the actual pixels in the DIB IntPtr dibPtr = Marshal.UnsafeAddrOfPinnedArrayElement(bytes, 0); IntPtr pixPtr = new IntPtr((int)dibPtr + bmpInfoHeader.biSize + (bmpInfoHeader.biClrUsed * 4)); // Get a GDI Bitmap IntPtr img = IntPtr.Zero; try { int st = GdiPlus.GdipCreateBitmapFromGdiDib(dibPtr, pixPtr, ref img); // Couldn't create bitmap, return null and log if ((st != 0) || (img == IntPtr.Zero)) { throw new DIBHelperException("Couldn't get DIB IntPtr"); } // Write the bitmap to a file of the specified type Guid clsid = GetCodecClsid(filePath); st = GdiPlus.GdipSaveImageToFile(img, filePath, ref clsid, IntPtr.Zero); if (st != 0) { throw new DIBHelperException("Couldn't write Dib to File"); } } finally { // Dispose of resources GdiPlus.GdipDisposeImage(img); } } finally { gcHandle.Free(); } }
public static string MongoPasswordDigest(string username, SecureString password) { using (var md5 = MD5.Create()) { var bytes = Utf8Encodings.Strict.GetBytes(username + ":mongo:"); md5.TransformBlock(bytes, 0, bytes.Length, null, 0); IntPtr unmanagedPassword = IntPtr.Zero; try { unmanagedPassword = Marshal.SecureStringToBSTR(password); var passwordChars = new char[password.Length]; GCHandle passwordCharsHandle = new GCHandle(); try { passwordCharsHandle = GCHandle.Alloc(passwordChars, GCHandleType.Pinned); Marshal.Copy(unmanagedPassword, passwordChars, 0, passwordChars.Length); var byteCount = Utf8Encodings.Strict.GetByteCount(passwordChars); var passwordBytes = new byte[byteCount]; GCHandle passwordBytesHandle = new GCHandle(); try { passwordBytesHandle = GCHandle.Alloc(passwordBytesHandle, GCHandleType.Pinned); Utf8Encodings.Strict.GetBytes(passwordChars, 0, passwordChars.Length, passwordBytes, 0); md5.TransformFinalBlock(passwordBytes, 0, passwordBytes.Length); return BsonUtils.ToHexString(md5.Hash); } finally { Array.Clear(passwordBytes, 0, passwordBytes.Length); if (passwordBytesHandle.IsAllocated) { passwordBytesHandle.Free(); } } } finally { Array.Clear(passwordChars, 0, passwordChars.Length); if (passwordCharsHandle.IsAllocated) { passwordCharsHandle.Free(); } } } finally { if (unmanagedPassword != IntPtr.Zero) { Marshal.ZeroFreeBSTR(unmanagedPassword); } } } }
public void Free() { if (!allocatedHandles.TryRemove(ToIntPtr(this), out _)) { throw new InvalidOperationException($"Allocated GC handle has already been freed."); } gch.Free(); }
public WaveRecorder(int deviceIndex, double sampleRate, int framesPerBuffer, AudioBufferAvailableDelegate bufferAvailable) { _bufferAvailable = bufferAvailable; var inputParams = new PaStreamParameters(); inputParams.device = deviceIndex; inputParams.channelCount = 2; inputParams.suggestedLatency = 0; inputParams.sampleFormat = PaSampleFormat.PaFloat32; var pe = PortAudioAPI.Pa_IsFormatSupported(ref inputParams, IntPtr.Zero, sampleRate); if (pe != PaError.paNoError) { throw new ApplicationException(pe.ToString()); } _gcHandle = GCHandle.Alloc(this); pe = PortAudioAPI.Pa_OpenStream( out _streamHandle, ref inputParams, IntPtr.Zero, sampleRate, (uint) framesPerBuffer, PaStreamFlags.PaNoFlag, _paCallback, (IntPtr) _gcHandle); if (pe != PaError.paNoError) { _gcHandle.Free(); throw new ApplicationException(pe.ToString()); } pe = PortAudioAPI.Pa_StartStream(_streamHandle); if (pe != PaError.paNoError) { PortAudioAPI.Pa_CloseStream(_streamHandle); _gcHandle.Free(); throw new ApplicationException(pe.ToString()); } }
public static ModuleInfo[] GetModuleInfos(int processId) { IntPtr ptr = (IntPtr) (-1); GCHandle handle = new GCHandle(); ArrayList list = new ArrayList(); try { ptr = Microsoft.Win32.NativeMethods.CreateToolhelp32Snapshot(8, processId); if (ptr == ((IntPtr) (-1))) { throw new Win32Exception(); } int num = Marshal.SizeOf(typeof(Microsoft.Win32.NativeMethods.WinModuleEntry)); int val = (num + 260) + 0x100; int[] numArray = new int[val / 4]; handle = GCHandle.Alloc(numArray, GCHandleType.Pinned); IntPtr ptr2 = handle.AddrOfPinnedObject(); Marshal.WriteInt32(ptr2, val); HandleRef ref2 = new HandleRef(null, ptr); if (Microsoft.Win32.NativeMethods.Module32First(ref2, ptr2)) { do { Microsoft.Win32.NativeMethods.WinModuleEntry structure = new Microsoft.Win32.NativeMethods.WinModuleEntry(); Marshal.PtrToStructure(ptr2, structure); ModuleInfo info = new ModuleInfo { baseName = Marshal.PtrToStringAnsi((IntPtr) (((long) ptr2) + num)), fileName = Marshal.PtrToStringAnsi((IntPtr) ((((long) ptr2) + num) + 0x100L)), baseOfDll = structure.modBaseAddr, sizeOfImage = structure.modBaseSize, Id = structure.th32ModuleID }; list.Add(info); Marshal.WriteInt32(ptr2, val); } while (Microsoft.Win32.NativeMethods.Module32Next(ref2, ptr2)); } } finally { if (handle.IsAllocated) { handle.Free(); } if (ptr != ((IntPtr) (-1))) { Microsoft.Win32.SafeNativeMethods.CloseHandle(new HandleRef(null, ptr)); } } ModuleInfo[] array = new ModuleInfo[list.Count]; list.CopyTo(array, 0); return array; }
unsafe void TessVertex(IntPtr tess, double *location, [In, Out] object data) { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluTessVertex((IntPtr)tess, (double *)location, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } }
public void GDIRead() { CheckDisposed(); if (source.IsLocked) throw new glResourceLockedException(source); gcHandle = GCHandle.Alloc(source.Data, GCHandleType.Pinned); var bitmapData = bitmap.LockBits(bitmapRect, ImageLockMode .ReadOnly, PixelFormat.Format32bppArgb); IntPtr dataHandle = gcHandle.AddrOfPinnedObject(); NativeMethods.CopyMemory(dataHandle, bitmapData.Scan0, (uint)source.SizeInBytes); bitmap.UnlockBits(bitmapData); gcHandle.Free(); }
public virtual void Run() { int instance = Kernel.GetModuleHandle(null); WndClassEx wndclass = new WndClassEx(); Msg msg = new Msg(); String clName = "Entry Area"; Win32.WinCB wcb = new Win32.WinCB(this.CallBack); root = System.Runtime.InteropServices.GCHandle.Alloc(wcb); wndclass.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(wndclass); wndclass.style = ClassStyle.HRedraw | ClassStyle.VRedraw; wndclass.lpfnWndProc = wcb; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = instance; this.instance = instance; wndclass.hIcon = User.LoadIcon(0, IconID.Application); wndclass.hCursor = User.LoadCursor(0, CursorID.Arrow); wndclass.hbrBackground = GDI.GetStockObject(Brush.White); wndclass.lpszMenuName = null; wndclass.lpszClassName = clName; wndclass.hIconSm = User.LoadIcon(0, IconID.Application); if (User.RegisterClassExA(wndclass) == 0) { throw new System.ApplicationException("Unable to Register Entry Dialog"); } wnd = User.CreateWindowEx(0, clName, clName, WinStyle.OverlappedWindow, 0, 0, xDim, yDim, 0, 0, instance, 0); if (wnd == 0) { throw new System.ApplicationException(Error.GetSystemErrorMessage()); } User.ShowWindow(wnd, ShowWindow.ShowNormal); User.UpdateWindow(wnd); while (User.GetMessage(msg, 0, 0, 0) != 0) { User.TranslateMessage(msg); User.DispatchMessage(msg); } root.Free(); }
public void PopulateCrlWrapperFields(byte[] CrlFileBinary) { var phCertStore = IntPtr.Zero; var pvContext = IntPtr.Zero; var hCrlData = new GCHandle(); var hCryptBlob = new GCHandle(); try { hCrlData = GCHandle.Alloc(CrlFileBinary, GCHandleType.Pinned); WinCrypt32.CRYPTOAPI_BLOB stCryptBlob; stCryptBlob.cbData = CrlFileBinary.Length; stCryptBlob.pbData = hCrlData.AddrOfPinnedObject(); hCryptBlob = GCHandle.Alloc(stCryptBlob, GCHandleType.Pinned); if (!WinCrypt32.CryptQueryObject( WinCrypt32.CERT_QUERY_OBJECT_BLOB, hCryptBlob.AddrOfPinnedObject(), WinCrypt32.CERT_QUERY_CONTENT_FLAG_CRL, WinCrypt32.CERT_QUERY_FORMAT_FLAG_BINARY, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref phCertStore, IntPtr.Zero, ref pvContext )) { throw new Win32Exception(Marshal.GetLastWin32Error(), "CRL is Corrupted."); } var stCrlContext = (WinCrypt32.CRL_CONTEXT)Marshal.PtrToStructure(pvContext, typeof(WinCrypt32.CRL_CONTEXT)); var stCrlInfo = (WinCrypt32.CRL_INFO)Marshal.PtrToStructure(stCrlContext.pCrlInfo, typeof(WinCrypt32.CRL_INFO)); _validUntil = ReadFromFileTime(stCrlInfo.NextUpdate); _validFrom = ReadFromFileTime(stCrlInfo.ThisUpdate); PopulateRevokedSerialNumbers(stCrlInfo); } finally { if (hCrlData.IsAllocated) hCrlData.Free(); if (hCryptBlob.IsAllocated) hCryptBlob.Free(); if (!pvContext.Equals(IntPtr.Zero)) { WinCrypt32.CertFreeCRLContext(pvContext); } } }
Int32 Build2DMipmapLevel(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, PixelFormat format, PixelType type, Int32 level, Int32 @base, Int32 max, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { return(Delegates.gluBuild2DMipmapLevels((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (PixelFormat)format, (PixelType)type, (Int32)level, (Int32)@base, (Int32)max, (IntPtr)data_ptr.AddrOfPinnedObject())); } finally { data_ptr.Free(); } } }
void TessBeginPolygon(IntPtr tess, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluTessBeginPolygon((IntPtr)tess, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } }
void NurbsCallbackData(IntPtr nurb, [In, Out] object userData) { unsafe { System.Runtime.InteropServices.GCHandle userData_ptr = System.Runtime.InteropServices.GCHandle.Alloc(userData, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluNurbsCallbackDataEXT((IntPtr)nurb, (IntPtr)userData_ptr.AddrOfPinnedObject()); } finally { userData_ptr.Free(); } } }
private void Dispose(bool disposing) { if (_disposed) { return; } _disposed = true; if (_handle == IntPtr.Zero) { return; } User32.DestroyWindow(_handle); _handle = IntPtr.Zero; gcHandle.Free(); }
public unsafe void Init(byte[] buffer, int offset, int capacityWords, int activeWords) { if (activeWords < capacityWords) Array.Clear(buffer, offset, capacityWords - activeWords); var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { var ptr = (byte*)handle.AddrOfPinnedObject(); base.Initialize(new IntPtr(ptr + offset), capacityWords, activeWords); this.handle = handle; handle = default(GCHandle); } finally { if (handle.IsAllocated) handle.Free(); } }
public static bool pump(IntPtr hwnd) { MSG msg = new MSG(); System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(msg); bool foundMessage = PeekMessage(out msg, hwnd, 0, 0, 0); handle.Free(); if (foundMessage) { TranslateMessage(ref msg); DispatchMessage(ref msg); } return(foundMessage); }
Int32 ScaleImage(PixelFormat format, Int32 wIn, Int32 hIn, PixelType typeIn, [In, Out] object dataIn, Int32 wOut, Int32 hOut, PixelType typeOut, [In, Out] object dataOut) { unsafe { System.Runtime.InteropServices.GCHandle dataIn_ptr = System.Runtime.InteropServices.GCHandle.Alloc(dataIn, System.Runtime.InteropServices.GCHandleType.Pinned); System.Runtime.InteropServices.GCHandle dataOut_ptr = System.Runtime.InteropServices.GCHandle.Alloc(dataOut, System.Runtime.InteropServices.GCHandleType.Pinned); try { return(Delegates.gluScaleImage((PixelFormat)format, (Int32)wIn, (Int32)hIn, (PixelType)typeIn, (IntPtr)dataIn_ptr.AddrOfPinnedObject(), (Int32)wOut, (Int32)hOut, (PixelType)typeOut, (IntPtr)dataOut_ptr.AddrOfPinnedObject())); } finally { dataIn_ptr.Free(); dataOut_ptr.Free(); } } }
void ResourceHandler_ReadResponse(object sender, CfxReadResponseEventArgs e) { int bytesToCopy = webResource.data.Length - bytesDone; if (bytesToCopy > e.BytesToRead) { bytesToCopy = e.BytesToRead; } Marshal.Copy(webResource.data, bytesDone, e.DataOut, bytesToCopy); e.BytesRead = bytesToCopy; bytesDone += bytesToCopy; e.SetReturnValue(true); if (bytesDone == webResource.data.Length) { gcHandle.Free(); } }
/// <summary> /// loads a texture from a stream containing raw bitmap data /// </summary> /// <param name="stream">stream to load from</param> /// <param name="width">width of texture</param> /// <param name="height">height of texture</param> /// <param name="mipLevels">number of MipMap level</param> /// <param name="format">format of texture</param> /// <returns>texture object</returns> private ITexture2d LoadRaw(Stream stream, int width, int height, int mipLevels, Purple.Graphics.Format format) { int countBytes = width * height * Purple.Graphics.GraphicsEngine.BitsPerPixel(format) / 8; byte[] data = new Byte[countBytes]; stream.Read(data, 0, countBytes); System.Drawing.Bitmap bitmap; // pin array System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(data); System.IntPtr ptr = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(data, 0); bitmap = new System.Drawing.Bitmap(width, height, width * 3, System.Drawing.Imaging.PixelFormat.Format24bppRgb, ptr); ITexture2d tex = TextureManager.Instance.Create(width, height, 1, Format.A8R8G8B8, TextureUsage.Normal); tex.CopyBitmap(bitmap, new System.Drawing.Rectangle(0, 0, width, height), System.Drawing.Point.Empty); bitmap.Dispose(); handle.Free(); return(tex); }
private void MainCycle() { var cb = new Event.D.evhttp_request_callback (RequestHandler); _httpCallbackHandle = GCHandle.Alloc (cb); Event.EvHttpSetAllowedMethods (_evHttp, EvHttpCmdType.All); Event.EvHttpSetGenCb (_evHttp, cb, GCHandle.ToIntPtr (_httpCallbackHandle)); var syncCb = new Event.D.event_callback (SyncCallback); _syncCbHandle = GCHandle.Alloc (syncCb); using (_syncCbEvent = Event.EventNew(_eventBase, -1, 0, syncCb, IntPtr.Zero)) { while (!_stop) { Event.EventBaseDispatch(_eventBase); } } //We've recieved loopbreak from actual Dispose, so dispose now DoDispose (); _httpCallbackHandle.Free (); _syncCbHandle.Free (); }
public override Object ReadGameData(Boolean forSpotter) { lock (this) { pCarsAPIStruct _pcarsapistruct = new pCarsAPIStruct(); if (!initialised) { if (!InitialiseInternal()) { throw new GameDataReadException("Failed to initialise shared memory"); } } try { using (var sharedMemoryStreamView = memoryMappedFile.CreateViewStream()) { BinaryReader _SharedMemoryStream = new BinaryReader(sharedMemoryStreamView); sharedMemoryReadBuffer = _SharedMemoryStream.ReadBytes(sharedmemorysize); handle = GCHandle.Alloc(sharedMemoryReadBuffer, GCHandleType.Pinned); _pcarsapistruct = (pCarsAPIStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(pCarsAPIStruct)); //Console.WriteLine(_pcarsapistruct.mSpeed); handle.Free(); } PCarsStructWrapper structWrapper = new PCarsStructWrapper(); structWrapper.ticksWhenRead = DateTime.Now.Ticks; structWrapper.data = _pcarsapistruct; if (!forSpotter && dumpToFile && dataToDump != null && _pcarsapistruct.mTrackLocation != null && _pcarsapistruct.mTrackLocation.Length > 0) { dataToDump.Add(structWrapper); } return structWrapper; } catch (Exception ex) { throw new GameDataReadException(ex.Message, ex); } } }
public static SafeGCHandle <T> Alloc <T>(T value, GCHandleType type) where T : class { SafeGCHandle <T> handle3; SafeGCHandle <T> handle = new SafeGCHandle <T>(); System.Runtime.InteropServices.GCHandle gcHandle = new System.Runtime.InteropServices.GCHandle(); try { gcHandle = System.Runtime.InteropServices.GCHandle.Alloc(value, type); handle.TakeHandle(ref gcHandle); handle3 = handle; } catch (Exception) { if (gcHandle.IsAllocated) { gcHandle.Free(); } throw; } return(handle3); }
public override Object ReadGameData(Boolean forSpotter) { lock (this) { RaceRoomShared _raceroomapistruct = new RaceRoomShared(); if (!initialised) { if (!InitialiseInternal()) { throw new GameDataReadException("Failed to initialise shared memory"); } } try { using (var sharedMemoryStreamView = memoryMappedFile.CreateViewStream()) { BinaryReader _SharedMemoryStream = new BinaryReader(sharedMemoryStreamView); sharedMemoryReadBuffer = _SharedMemoryStream.ReadBytes(sharedmemorysize); handle = GCHandle.Alloc(sharedMemoryReadBuffer, GCHandleType.Pinned); _raceroomapistruct = (RaceRoomShared)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(RaceRoomShared)); handle.Free(); } R3EStructWrapper structWrapper = new R3EStructWrapper(); structWrapper.ticksWhenRead = DateTime.Now.Ticks; structWrapper.data = _raceroomapistruct; if (!forSpotter && dumpToFile && dataToDump != null) { dataToDump.Add(structWrapper); } return structWrapper; } catch (Exception ex) { throw new GameDataReadException(ex.Message, ex); } } }
public static Signal DeserializeFromStream(Stream stream) { Contract.Requires<ArgumentNullException>(stream != null); using (var reader = new BinaryReader(stream)) { var streamHeader = Encoding.ASCII.GetString(reader.ReadBytes(4)); if (!streamHeader.StartsWith("TMB")) { throw new NotSupportedException($"File is not supported. Invalid header: {streamHeader}."); } var handle = new GCHandle(); SignalHeader header; try { var data = reader.ReadBytes(Marshal.SizeOf(typeof (SignalHeader))); handle = GCHandle.Alloc(data, GCHandleType.Pinned); header = (SignalHeader) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof (SignalHeader)); } finally { if (handle.IsAllocated) { handle.Free(); } } var buffer = new byte[stream.Length - stream.Position]; reader.BaseStream.Read(buffer, 0, buffer.Length); var values = Enumerable.Range(0, buffer.Length) .Where(x => x%4 == 0) .Select(i => BitConverter.ToSingle(buffer, i)) .Select(Convert.ToDouble) .ToArray(); return new Signal(header, values); } }
public static bool GetProcessModules(Process process, out string[] modules) { System.Collections.Generic.List <string> list = new System.Collections.Generic.List <string>(); System.IntPtr hProcess = Process32.OpenProcess(1040u, 0, (uint)process.Id); System.IntPtr[] array = new System.IntPtr[1024]; uint num = 0u; uint cb = (uint)(System.Runtime.InteropServices.Marshal.SizeOf(typeof(System.IntPtr)) * array.Length); System.Runtime.InteropServices.GCHandle gCHandle = System.Runtime.InteropServices.GCHandle.Alloc(array, System.Runtime.InteropServices.GCHandleType.Pinned); System.IntPtr lphModule = gCHandle.AddrOfPinnedObject(); if (Process32.EnumProcessModules(hProcess, lphModule, cb, out num) == 1) { int num2 = (int)((ulong)num / (ulong)((long)System.Runtime.InteropServices.Marshal.SizeOf(typeof(System.IntPtr)))); for (int i = 0; i < num2; i++) { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(1024); Process32.GetModuleFileNameEx(hProcess, array[i], stringBuilder, stringBuilder.Capacity); list.Add(stringBuilder.ToString()); } } gCHandle.Free(); modules = list.ToArray(); return(true); }
public static unsafe void Decode(CodeInfo nci, DecodedResult dr) { _CodeInfo* ci = null; _DecodedInst* insts = null; var gch = new GCHandle(); uint usedInstructionsCount = 0; try { if ((ci = AcquireCodeInfoStruct(nci, out gch)) == null) throw new OutOfMemoryException(); var maxInstructions = dr.MaxInstructions; if ((insts = (_DecodedInst*) Malloc(maxInstructions*sizeof (_DecodedInst))) == null) throw new OutOfMemoryException(); distorm_decode64(ci->codeOffset, ci->code, ci->codeLen, ci->dt, insts, (uint) maxInstructions, &usedInstructionsCount); var dinsts = new DecodedInst[usedInstructionsCount]; for (var i = 0; i < usedInstructionsCount; i++) dinsts[i] = CreateDecodedInstObj(&insts[i]); dr.Instructions = dinsts; } finally { /* In case of an error, jInsts will get cleaned automatically. */ if (gch.IsAllocated) gch.Free(); if (ci != null) Free(ci); if (insts != null) Free(insts); } }
public void SetPhySimulationEventCallback(PhySimulationEventCallback cb) { if (cb == null) { SDK_PhySceneDesc_SetContactCallBack(CoreObject, IntPtr.Zero, null, null, null, null, null, null, PhySimulationEventCallback.pxSimulationFilterShader); if (SimulationEventCallbackHandle != null) { SimulationEventCallbackHandle.Free(); } } else { SimulationEventCallback = cb; SimulationEventCallbackHandle = System.Runtime.InteropServices.GCHandle.Alloc(cb, GCHandleType.WeakTrackResurrection); SDK_PhySceneDesc_SetContactCallBack(CoreObject, System.Runtime.InteropServices.GCHandle.ToIntPtr(SimulationEventCallbackHandle), cb.onContact, cb.onTrigger, cb.onConstraintBreak, cb.onWake, cb.onSleep, cb.onAdvance, PhySimulationEventCallback.pxSimulationFilterShader); } }
public void Listen(int backlog, Action<UvStreamHandle, int, Exception, object> callback, object state) { if (_listenVitality.IsAllocated) { throw new InvalidOperationException("TODO: Listen may not be called more than once"); } try { _listenCallback = callback; _listenState = state; _listenVitality = GCHandle.Alloc(this, GCHandleType.Normal); _uv.listen(this, backlog, _uv_connection_cb); } catch { _listenCallback = null; _listenState = null; if (_listenVitality.IsAllocated) { _listenVitality.Free(); } throw; } }
/// <summary> /// Read an UIImage, covert the data and save it to the native pointer /// </summary> /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam> /// <param name="image">The input image</param> /// <param name="dest">The native pointer where the image pixels values will be saved to.</param> /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param> /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param> /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param> /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param> /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param> /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param> public static void ReadImageToTensor <T>( UIImage imageOriginal, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } UIImage image; if (inputHeight > 0 || inputWidth > 0) { image = imageOriginal.Scale(new CGSize(inputWidth, inputHeight)); //image.Dispose(); //image = resized; } else { image = imageOriginal; } try { int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } } finally { if (image != imageOriginal) { image.Dispose(); } } }
/// <summary> /// Read the image file into a Tensorflow tensor /// </summary> /// <typeparam name="T">The tensor data type, e.g. float</typeparam> /// <param name="fileName">The name of the image file</param> /// <param name="inputHeight">The height of the input tensor. If zero or negative, will use the image height from the file</param> /// <param name="inputWidth">The width of the input tensor. If zero or negative, will use the image width from the file</param> /// <param name="inputMean">The input mean, will be subtracted from the image pixel value</param> /// <param name="scale">The optional scale, after input means is substracted, the pixel value will multiply with the scale to produce the tensor value</param> /// <param name="flipUpSideDown">If true, the image will be flipped upside down</param> /// <param name="swapBR">If true, the blue and red channels will be swapped</param> /// <returns>The tensorflow tensor.</returns> public static Tensor ReadTensorFromImageFile <T>( String fileName, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { #if __ANDROID__ return(NativeReadTensorFromImageFile <T>(fileName, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, swapBR)); #elif __IOS__ UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)image.Size.Height, (int)image.Size.Width, 3 }); System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length); return(t); #else FileInfo fi = new FileInfo(fileName); String extension = fi.Extension.ToLower(); //Use tensorflow to decode the following image formats if ((typeof(T) == typeof(float)) && (extension.Equals(".jpeg") || extension.Equals(".jpg") || extension.Equals(".png") || extension.Equals(".gif"))) { using (Graph graph = new Graph()) { Operation input = graph.Placeholder(DataType.String); //output dimension [height, width, 3] where 3 is the number of channels //DecodeJpeg can decode JPEG, PNG and GIF Operation jpegDecoder = graph.DecodeJpeg(input, 3); Operation floatCaster = graph.Cast(jpegDecoder, DstT: DataType.Float); //cast to float Tensor zeroConst = new Tensor(0); Operation zeroConstOp = graph.Const(zeroConst, zeroConst.Type, opName: "zeroConstOp"); Operation dimsExpander = graph.ExpandDims(floatCaster, zeroConstOp); //turn it to dimension [1, height, width, 3] Operation resized; bool resizeRequired = (inputHeight > 0) && (inputWidth > 0); if (resizeRequired) { Tensor size = new Tensor(new int[] { inputHeight, inputWidth }); // new size; Operation sizeOp = graph.Const(size, size.Type, opName: "size"); resized = graph.ResizeBilinear(dimsExpander, sizeOp); //resize image } else { resized = dimsExpander; } Tensor mean = new Tensor(inputMean); Operation meanOp = graph.Const(mean, mean.Type, opName: "mean"); Operation subtracted = graph.Sub(resized, meanOp); Tensor scaleTensor = new Tensor(scale); Operation scaleOp = graph.Const(scaleTensor, scaleTensor.Type, opName: "scale"); Operation scaled = graph.Mul(subtracted, scaleOp); Operation swapedBR; if (swapBR) { Tensor threeConst = new Tensor(new int[] { 3 }); Operation threeConstOp = graph.Const(threeConst, threeConst.Type, "threeConstOp"); swapedBR = graph.ReverseV2(scaled, threeConstOp, "swapBR"); } else { swapedBR = scaled; } Operation flipped; if (flipUpSideDown) { Tensor oneConst = new Tensor(new int[] { 1 }); Operation oneConstOp = graph.Const(oneConst, oneConst.Type, "oneConstOp"); flipped = graph.ReverseV2(swapedBR, oneConstOp, "flipUpSideDownOp"); } else { flipped = swapedBR; } using (Session session = new Session(graph)) { Tensor imageTensor = Tensor.FromString(File.ReadAllBytes(fileName)); Tensor[] imageResults = session.Run(new Output[] { input }, new Tensor[] { imageTensor }, new Output[] { flipped }); return(imageResults[0]); } } } else { return(NativeReadTensorFromImageFile <T>(fileName, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, swapBR)); } #endif }
/// <summary> /// Unprotect /// </summary> public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) { if (encryptedData == null) throw new ArgumentNullException("encryptedData"); GCHandle pbDataIn = new GCHandle(); GCHandle pOptionalEntropy = new GCHandle(); CAPI.CRYPTOAPI_BLOB userData = new CAPI.CRYPTOAPI_BLOB(); try { pbDataIn = GCHandle.Alloc(encryptedData, GCHandleType.Pinned); CAPI.CRYPTOAPI_BLOB dataIn = new CAPI.CRYPTOAPI_BLOB(); dataIn.cbData = (uint)encryptedData.Length; dataIn.pbData = pbDataIn.AddrOfPinnedObject(); CAPI.CRYPTOAPI_BLOB entropy = new CAPI.CRYPTOAPI_BLOB(); if (optionalEntropy != null) { pOptionalEntropy = GCHandle.Alloc(optionalEntropy, GCHandleType.Pinned); entropy.cbData = (uint)optionalEntropy.Length; entropy.pbData = pOptionalEntropy.AddrOfPinnedObject(); } uint dwFlags = CAPI.CRYPTPROTECT_UI_FORBIDDEN; if (scope == DataProtectionScope.LocalMachine) dwFlags |= CAPI.CRYPTPROTECT_LOCAL_MACHINE; unsafe { if (!CAPI.CryptUnprotectData(new IntPtr(&dataIn), IntPtr.Zero, new IntPtr(&entropy), IntPtr.Zero, IntPtr.Zero, dwFlags, new IntPtr(&userData))) throw new CryptographicException(Marshal.GetLastWin32Error()); } // In some cases, the API would fail due to OOM but simply return a null pointer. if (userData.pbData == IntPtr.Zero) throw new OutOfMemoryException(); byte[] data = new byte[(int)userData.cbData]; Marshal.Copy(userData.pbData, data, 0, data.Length); return data; } finally { if (pbDataIn.IsAllocated) pbDataIn.Free(); if (pOptionalEntropy.IsAllocated) pOptionalEntropy.Free(); if (userData.pbData != IntPtr.Zero) { CAPI.ZeroMemory(userData.pbData, userData.cbData); CAPI.LocalFree(userData.pbData); } } }
public static void ReadImageFileToTensor(String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f) { #if __ANDROID__ Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __IOS__ UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __UNIFIED__ NSImage image = new NSImage(fileName); if (inputHeight > 0 || inputWidth > 0) { NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight)); resized.LockFocus(); image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f); resized.UnlockFocus(); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #else if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows) { //Do something for Windows System.Drawing.Bitmap bmp = new Bitmap(fileName); if (inputHeight > 0 || inputWidth > 0) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; //bmp.Save("tmp.png"); } byte[] byteValues = new byte[bmp.Width * bmp.Height * 3]; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); System.Runtime.InteropServices.Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length); bmp.UnlockBits(bd); float[] floatValues = new float[bmp.Width * bmp.Height * 3]; for (int i = 0; i < byteValues.Length; ++i) { floatValues[i] = ((float)byteValues[i] - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else { throw new Exception("Not implemented"); } #endif }
//------------------------------------------------------------------- internal unsafe static int AcceptSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.Secur32.ContextFlags outFlags) { #if TRACE_VERBOSE GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex"); GlobalLog.Print(" credential = " + inCredentials.ToString()); GlobalLog.Print(" refContext = " + Logging.ObjectToString(refContext)); GlobalLog.Print(" inFlags = " + inFlags); if (inSecBuffers == null) { GlobalLog.Print(" inSecBuffers = (null)"); } else { GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length); } #endif GlobalLog.Assert(outSecBuffer != null, "SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null"); GlobalLog.Assert(inSecBuffer == null || inSecBuffers == null, "SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null"); if (inCredentials == null) { throw new ArgumentNullException("inCredentials"); } Interop.Secur32.SecurityBufferDescriptor inSecurityBufferDescriptor = null; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1); } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(inSecBuffers.Length); } Interop.Secur32.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.Secur32.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.Secur32.SSPIHandle contextHandle = new Interop.Secur32.SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); var inUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (inSecurityBufferDescriptor != null) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type); #endif } } } var outUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[1]; fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr; // Copy the SecurityBuffer content into unmanaged place holder. outUnmanagedBuffer[0].count = outSecBuffer.size; outUnmanagedBuffer[0].type = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].token = IntPtr.Zero; } else { outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor, inFlags, endianness, refContext, outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext Marshalling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer[0].count; outSecBuffer.type = outUnmanagedBuffer[0].type; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + Logging.ObjectToString(refContext)); return errorCode; }
public static byte[] CreateSelfSignCertificatePfx( string x500, DateTime startTime, DateTime endTime, SecureString password) { byte[] pfxData; if (x500 == null) { x500 = ""; } SystemTime startSystemTime = ToSystemTime(startTime); SystemTime endSystemTime = ToSystemTime(endTime); string containerName = Guid.NewGuid().ToString(); var dataHandle = new GCHandle(); var providerContext = IntPtr.Zero; var cryptKey = IntPtr.Zero; var certContext = IntPtr.Zero; var certStore = IntPtr.Zero; var storeCertContext = IntPtr.Zero; var passwordPtr = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { Check(NativeMethods.CryptAcquireContextW( out providerContext, containerName, null, 1, // PROV_RSA_FULL 8)); // CRYPT_NEWKEYSET Check(NativeMethods.CryptGenKey( providerContext, 1, // AT_KEYEXCHANGE 1, // CRYPT_EXPORTABLE out cryptKey)); IntPtr errorStringPtr; int nameDataLength = 0; byte[] nameData; // errorStringPtr gets a pointer into the middle of the x500 string, // so x500 needs to be pinned until after we've copied the value // of errorStringPtr. dataHandle = GCHandle.Alloc(x500, GCHandleType.Pinned); if (!NativeMethods.CertStrToNameW( 0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING dataHandle.AddrOfPinnedObject(), 3, // CERT_X500_NAME_STR = 3 IntPtr.Zero, null, ref nameDataLength, out errorStringPtr)) { string error = Marshal.PtrToStringUni(errorStringPtr); throw new ArgumentException(error); } nameData = new byte[nameDataLength]; if (!NativeMethods.CertStrToNameW( 0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING dataHandle.AddrOfPinnedObject(), 3, // CERT_X500_NAME_STR = 3 IntPtr.Zero, nameData, ref nameDataLength, out errorStringPtr)) { string error = Marshal.PtrToStringUni(errorStringPtr); throw new ArgumentException(error); } dataHandle.Free(); dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned); var nameBlob = new CryptoApiBlob( nameData.Length, dataHandle.AddrOfPinnedObject()); var kpi = new CryptKeyProviderInformation(); kpi.ContainerName = containerName; kpi.ProviderType = 1; // PROV_RSA_FULL kpi.KeySpec = 1; // AT_KEYEXCHANGE certContext = NativeMethods.CertCreateSelfSignCertificate( providerContext, ref nameBlob, 0, ref kpi, IntPtr.Zero, // default = SHA1RSA ref startSystemTime, ref endSystemTime, IntPtr.Zero); Check(certContext != IntPtr.Zero); dataHandle.Free(); certStore = NativeMethods.CertOpenStore( "Memory", // sz_CERT_STORE_PROV_MEMORY 0, IntPtr.Zero, 0x2000, // CERT_STORE_CREATE_NEW_FLAG IntPtr.Zero); Check(certStore != IntPtr.Zero); Check(NativeMethods.CertAddCertificateContextToStore( certStore, certContext, 1, // CERT_STORE_ADD_NEW out storeCertContext)); NativeMethods.CertSetCertificateContextProperty( storeCertContext, 2, // CERT_KEY_PROV_INFO_PROP_ID 0, ref kpi); if (password != null) { passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password); } var pfxBlob = new CryptoApiBlob(); Check(NativeMethods.PFXExportCertStoreEx( certStore, ref pfxBlob, passwordPtr, IntPtr.Zero, 7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY pfxData = new byte[pfxBlob.DataLength]; dataHandle = GCHandle.Alloc(pfxData, GCHandleType.Pinned); pfxBlob.Data = dataHandle.AddrOfPinnedObject(); Check(NativeMethods.PFXExportCertStoreEx( certStore, ref pfxBlob, passwordPtr, IntPtr.Zero, 7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY dataHandle.Free(); } finally { if (passwordPtr != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr); } if (dataHandle.IsAllocated) { dataHandle.Free(); } if (certContext != IntPtr.Zero) { NativeMethods.CertFreeCertificateContext(certContext); } if (storeCertContext != IntPtr.Zero) { NativeMethods.CertFreeCertificateContext(storeCertContext); } if (certStore != IntPtr.Zero) { NativeMethods.CertCloseStore(certStore, 0); } if (cryptKey != IntPtr.Zero) { NativeMethods.CryptDestroyKey(cryptKey); } if (providerContext != IntPtr.Zero) { NativeMethods.CryptReleaseContext(providerContext, 0); NativeMethods.CryptAcquireContextW( out providerContext, containerName, null, 1, // PROV_RSA_FULL 0x10); // CRYPT_DELETEKEYSET } } return pfxData; }
/// <summary> /// Four channel 8-bit unsigned 3D trilinear interpolated look-up-table color conversion, not affecting alpha.<para/> /// Alpha channel is the last channel and is not processed.<para/> /// The LUT is derived from a set of user defined mapping points through trilinear interpolation. /// </summary> /// <param name="pValues">Device pointer to aLevels[2] number of contiguous 2D x,y planes of 4-byte packed RGBX values /// containing the user defined base OUTPUT values at that x,y, and z (R,G,B) level location. Each level must contain x * y 4-byte /// packed pixel values (4th byte is used for alignement only and is ignored) in row (x) order.</param> /// <param name="pLevels0">array, cube edge 0, with user defined INPUT level values.</param> /// <param name="pLevels1">array, cube edge 1, with user defined INPUT level values.</param> /// <param name="pLevels2">array, cube edge 2, with user defined INPUT level values.</param> /// <param name="aLevels">Host pointer to an array of 3 user defined number of input/output mapping points, one per 3D cube edge. /// aLevels[0] represents the number of x axis levels (Red), aLevels[1] represents the number of y axis levels (Green), /// and aLevels[2] represets the number of z axis levels (Blue).</param> public void LUTTrilinearA(CudaDeviceVariable<int> pValues, int[] pLevels0, int[] pLevels1, int[] pLevels2, int[] aLevels) { GCHandle h0 = new GCHandle(), h1 = new GCHandle(), h2 = new GCHandle(); try { h0 = GCHandle.Alloc(pLevels0, GCHandleType.Pinned); h1 = GCHandle.Alloc(pLevels1, GCHandleType.Pinned); h2 = GCHandle.Alloc(pLevels2, GCHandleType.Pinned); IntPtr[] ptrsLevels = new IntPtr[3]; ptrsLevels[0] = h0.AddrOfPinnedObject(); ptrsLevels[1] = h1.AddrOfPinnedObject(); ptrsLevels[2] = h2.AddrOfPinnedObject(); status = NPPNativeMethods.NPPi.ColorLUTTrilinear.nppiLUT_Trilinear_8u_AC4IR(_devPtrRoi, _pitch, _sizeRoi, pValues.DevicePointer, ptrsLevels, aLevels); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiLUT_Trilinear_8u_AC4IR", status)); NPPException.CheckNppStatus(status, this); } catch (Exception) { throw; } finally { h0.Free(); h1.Free(); h2.Free(); } }
/// <summary> /// Read an image file, covert the data and save it to the native pointer /// </summary> /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam> /// <param name="fileName">The name of the image file</param> /// <param name="dest">The native pointer where the image pixels values will be saved to.</param> /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param> /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param> /// <param name="inputMean">The mean value, it will be substracted from the input image pixel values</param> /// <param name="scale">The scale, after mean is substracted, the scale will be used to multiply the pixel values</param> /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param> /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param> public static void ReadImageFileToTensor <T>( String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { if (!File.Exists(fileName)) { throw new FileNotFoundException(String.Format("File {0} do not exist.", fileName)); } #if __ANDROID__ Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } if (flipUpSideDown) { Matrix matrix = new Matrix(); matrix.PostScale(1, -1, bmp.Width / 2, bmp.Height / 2); Bitmap flipped = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true); bmp.Dispose(); bmp = flipped; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } #elif __IOS__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __UNIFIED__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } //if (swapBR) // throw new NotImplementedException("swapBR is Not implemented"); NSImage image = new NSImage(fileName); if (inputHeight > 0 || inputWidth > 0) { NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight)); resized.LockFocus(); image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f); resized.UnlockFocus(); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE Texture2D texture = ReadTexture2DFromFile(fileName); ReadTensorFromTexture2D <T>(texture, dest, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, false); #else //if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { //Read the file using Bitmap class System.Drawing.Bitmap bmp = new Bitmap(fileName); if (inputHeight > 0 || inputWidth > 0) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; //bmp.Save("tmp.png"); } if (flipUpSideDown) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); } int bmpWidth = bmp.Width; int bmpHeight = bmp.Height; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmpWidth, bmpHeight), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); int stride = bd.Stride; byte[] byteValues = new byte[bmpHeight * stride]; Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length); bmp.UnlockBits(bd); if (typeof(T) == typeof(float)) { int imageSize = bmpWidth * bmpHeight; float[] floatValues = new float[imageSize * 3]; if (swapBR) { int idx = 0; int rowOffset = 0; for (int i = 0; i < bmpHeight; ++i) { int rowPtr = rowOffset; for (int j = 0; j < bmpWidth; ++j) { float b = ((float)byteValues[rowPtr++] - inputMean) * scale; float g = ((float)byteValues[rowPtr++] - inputMean) * scale; float r = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = r; floatValues[idx++] = g; floatValues[idx++] = b; } rowOffset += stride; } } else { int idx = 0; int rowOffset = 0; for (int i = 0; i < bmpHeight; ++i) { int rowPtr = rowOffset; for (int j = 0; j < bmpWidth; ++j) { floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; } rowOffset += stride; } } Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { int imageSize = bmp.Width * bmp.Height; if (swapBR) { int idx = 0; for (int i = 0; i < bmpHeight; ++i) { int offset = i * stride; for (int j = 0; j < bmpWidth; ++j) { byte b = (byte)(((float)byteValues[offset++] - inputMean) * scale); byte g = (byte)(((float)byteValues[offset++] - inputMean) * scale); byte r = (byte)(((float)byteValues[offset++] - inputMean) * scale); byteValues[idx++] = r; byteValues[idx++] = g; byteValues[idx++] = b; } } } else { int idx = 0; for (int i = 0; i < bmpHeight; ++i) { int offset = i * stride; for (int j = 0; j < bmpWidth * 3; ++j) { byteValues[idx++] = (byte)(((float)byteValues[offset++] - inputMean) * scale); } } } Marshal.Copy(byteValues, 0, dest, imageSize * 3); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } } /* * else //Unix * { * //if (flipUpSideDown) * // throw new NotImplementedException("Flip Up Side Down is Not implemented"); * * throw new NotImplementedException("Not implemented"); * }*/ #endif }
public static void ReadImageFileToTensor <T>( String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { #if __ANDROID__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } if (swapBR) { throw new NotImplementedException("swapBR is Not implemented"); } Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __IOS__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } if (swapBR) { throw new NotImplementedException("swapBR is Not implemented"); } UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __UNIFIED__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } if (swapBR) { throw new NotImplementedException("swapBR is Not implemented"); } NSImage image = new NSImage(fileName); if (inputHeight > 0 || inputWidth > 0) { NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight)); resized.LockFocus(); image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f); resized.UnlockFocus(); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE Texture2D texture = ReadTexture2DFromFile(fileName); ReadTensorFromTexture2D <T>(texture, dest, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, false); #else if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows) { //Do something for Windows System.Drawing.Bitmap bmp = new Bitmap(fileName); if (inputHeight > 0 || inputWidth > 0) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; //bmp.Save("tmp.png"); } if (flipUpSideDown) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); } byte[] byteValues = new byte[bmp.Width * bmp.Height * 3]; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length); bmp.UnlockBits(bd); if (typeof(T) == typeof(float)) { int imageSize = bmp.Width * bmp.Height; float[] floatValues = new float[imageSize * 3]; if (swapBR) { for (int i = 0; i < imageSize; ++i) { floatValues[i * 3] = (byte)(((float)byteValues[i * 3 + 2] - inputMean) * scale); floatValues[i * 3 + 1] = (byte)(((float)byteValues[i * 3 + 1] - inputMean) * scale); floatValues[i * 3 + 2] = (byte)(((float)byteValues[i * 3 + 0] - inputMean) * scale); } } else { for (int i = 0; i < byteValues.Length; ++i) { floatValues[i] = ((float)byteValues[i] - inputMean) * scale; } } Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { if (swapBR) { int imageSize = bmp.Width * bmp.Height; //byte[] bValues = new byte[imageSize * 3]; for (int i = 0; i < imageSize; ++i) { byte c0 = (byte)(((float)byteValues[i * 3 + 2] - inputMean) * scale); byte c1 = (byte)(((float)byteValues[i * 3 + 1] - inputMean) * scale); byte c2 = (byte)(((float)byteValues[i * 3 + 0] - inputMean) * scale); byteValues[i * 3] = c0; byteValues[i * 3 + 1] = c1; byteValues[i * 3 + 2] = c2; } } else { if (!(inputMean == 0.0f && scale == 1.0f)) { for (int i = 0; i < byteValues.Length; ++i) { byteValues[i] = (byte)(((float)byteValues[i] - inputMean) * scale); } } } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new Exception(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } } else //Unix { if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } throw new Exception("Not implemented"); } #endif }
public static Tensor ReadTensorFromImageFile(String fileName, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, Status status = null) { #if __ANDROID__ Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } Tensor t = new Tensor(DataType.Float, new int[] { 1, bmp.Height, bmp.Width, 3 }); System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length); return(t); #elif __IOS__ UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)image.Size.Height, (int)image.Size.Width, 3 }); System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length); return(t); #else if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows) { Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)inputHeight, (int)inputWidth, 3 }); NativeImageIO.ReadImageFileToTensor(fileName, t.DataPointer, inputHeight, inputWidth, inputMean, scale); return(t); } else { using (StatusChecker checker = new StatusChecker(status)) { var graph = new Graph(); Operation input = graph.Placeholder(DataType.String); Operation jpegDecoder = graph.DecodeJpeg(input, 3); //dimension 3 Operation floatCaster = graph.Cast(jpegDecoder, DstT: DataType.Float); //cast to float Tensor axis = new Tensor(0); Operation axisOp = graph.Const(axis, axis.Type, opName: "axis"); Operation dimsExpander = graph.ExpandDims(floatCaster, axisOp); //turn it to dimension [1,3] Operation resized; bool resizeRequired = (inputHeight > 0) && (inputWidth > 0); if (resizeRequired) { Tensor size = new Tensor(new int[] { inputHeight, inputWidth }); // new size; Operation sizeOp = graph.Const(size, size.Type, opName: "size"); resized = graph.ResizeBilinear(dimsExpander, sizeOp); //resize image } else { resized = dimsExpander; } Tensor mean = new Tensor(inputMean); Operation meanOp = graph.Const(mean, mean.Type, opName: "mean"); Operation substracted = graph.Sub(resized, meanOp); Tensor scaleTensor = new Tensor(scale); Operation scaleOp = graph.Const(scaleTensor, scaleTensor.Type, opName: "scale"); Operation scaled = graph.Mul(substracted, scaleOp); Session session = new Session(graph); Tensor imageTensor = Tensor.FromString(File.ReadAllBytes(fileName), status); Tensor[] imageResults = session.Run(new Output[] { input }, new Tensor[] { imageTensor }, new Output[] { scaled }); return(imageResults[0]); } } #endif }
public void Dispose() { Array.Clear(_data, 0, _data.Length); _gcHandle.Free(); }
/// <summary> /// Read an UIImage, covert the data and save it to the native pointer /// </summary> /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam> /// <param name="image">The input image</param> /// <param name="dest">The native pointer where the image pixels values will be saved to.</param> /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param> /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param> /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param> /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param> /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param> /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param> public static void ReadImageToTensor <T>( UIImage image, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { if (inputHeight <= 0) { inputHeight = (int)image.Size.Height; } if (inputWidth <= 0) { inputWidth = (int)image.Size.Width; } int[] intValues = new int[inputWidth * inputHeight]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), inputWidth, inputHeight, 8, inputWidth * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), new CGSize(inputWidth, inputHeight)), cgimage); } if (typeof(T) == typeof(float)) { Emgu.TF.Util.Toolbox.Pixel32ToPixelFloat( handle.AddrOfPinnedObject(), inputWidth, inputHeight, inputMean, scale, flipUpSideDown, swapBR, dest ); } else if (typeof(T) == typeof(byte)) { Emgu.TF.Util.Toolbox.Pixel32ToPixelByte( handle.AddrOfPinnedObject(), inputWidth, inputHeight, inputMean, scale, flipUpSideDown, swapBR, dest ); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } handle.Free(); }
[System.Security.SecurityCritical] // auto-generated internal static void DisposeDelegateInvocation(GCHandle delegateCallToken) { delegateCallToken.Free(); }
/// <summary> /// Sets the security settings for the proxy. /// </summary> public static void SetProxySecurity(object server, UserIdentity user) { // allocate the GCHandle hUserName = GCHandle.Alloc(user.Username, GCHandleType.Pinned); GCHandle hPassword = GCHandle.Alloc(user.Password, GCHandleType.Pinned); GCHandle hDomain = GCHandle.Alloc(user.Domain, GCHandleType.Pinned); GCHandle hIdentity = new GCHandle(); // create identity structure. COAUTHIDENTITY authIdentity = new COAUTHIDENTITY(); authIdentity.User = hUserName.AddrOfPinnedObject(); authIdentity.UserLength = (uint)((user.Username != null) ? user.Username.Length : 0); authIdentity.Password = hPassword.AddrOfPinnedObject(); authIdentity.PasswordLength = (uint)((user.Password != null) ? user.Password.Length : 0); authIdentity.Domain = hDomain.AddrOfPinnedObject(); authIdentity.DomainLength = (uint)((user.Domain != null) ? user.Domain.Length : 0); authIdentity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; hIdentity = GCHandle.Alloc(authIdentity, GCHandleType.Pinned); try { SetProxySecurity(server, hIdentity.AddrOfPinnedObject()); } finally { hUserName.Free(); hPassword.Free(); hDomain.Free(); hIdentity.Free(); } }
// // Summary: // Logs the event for the appropriate infocard error code. This code should // match the entries in messages,mc // Parameters: // code - the event code to log // Notes: // This code may need to be extended to support an array of string parameters. We will do this if our event // log messages require it. // private static void LogEvent(EventCode code, string message, EventLogEntryType type) { using (SafeEventLogHandle handle = SafeEventLogHandle.Construct()) { string parameter = message; if (null != handle) { if (String.IsNullOrEmpty(parameter)) { parameter = SR.GetString(SR.GeneralExceptionMessage); } // // Report event expects a LPCTSTR* lpStrings. Use GCHandle, instead // of writing code with unsafe because InfoCard client uses this // and our client cannot contain any unsafe code. // // // This is the array of LPCTSTRs // IntPtr[] stringRoots = new IntPtr[1]; // // This is to pin the parameter string itself. Use an array here if you want more than 1 string // GCHandle stringParamHandle = new GCHandle(); // // This is to pin the pointer to the array of LPCTSTRs // GCHandle stringsRootHandle = new GCHandle(); try { // // Pin the IntPtrs (ie array of LPCTSTRs) // stringsRootHandle = GCHandle.Alloc(stringRoots, GCHandleType.Pinned); // // Pin the parameter string itself // stringParamHandle = GCHandle.Alloc(parameter, GCHandleType.Pinned); // // Give the intptr address of the pinned string // stringRoots[0] = stringParamHandle.AddrOfPinnedObject(); // // From msdn: The interop marshaler passes only the handle [2nd arg to constructor in our case] // to unmanaged code, and guarantees that the wrapper (passed as the first parameter // to the constructor of the HandleRef) remains alive for the duration of the [PInvoke] call. // HandleRef data = new HandleRef(handle, stringsRootHandle.AddrOfPinnedObject()); SecurityIdentifier sid = WindowsIdentity.GetCurrent().User; byte[] sidBA = new byte[sid.BinaryLength]; sid.GetBinaryForm(sidBA, 0); if (!ReportEvent( handle, (short)type, (ushort)InfoCardEventCategory.General, (uint)code, sidBA, 1, 0, data, null)) { // // Errors in the eventlog API should be ignored by applications // int error = Marshal.GetLastWin32Error(); TraceDebug("Failed to report the event with error {0}", error); } } finally { if (stringsRootHandle.IsAllocated) { stringsRootHandle.Free(); } if (stringParamHandle.IsAllocated) { stringParamHandle.Free(); } } } } }
public MidiClient (string name) { using (var nsstr = new NSString (name)){ gch = GCHandle.Alloc (this); int code = MIDIClientCreate (nsstr.Handle, ClientCallback, GCHandle.ToIntPtr (gch), out handle); if (code != 0){ gch.Free (); handle = IntPtr.Zero; throw new MidiException ((MidiError) code); } Name = name; } }
public static void RegisterApplication(PeerApplication application, PeerApplicationRegistrationType type) { PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand(); if (application == null){ throw new ArgumentNullException("application"); } if (application.Path == null){ throw new ArgumentException(SR.GetString(SR.Collab_AppRegNoPathError)); } if ((type < PeerApplicationRegistrationType.CurrentUser) || (type > PeerApplicationRegistrationType.AllUsers)){ throw new ArgumentOutOfRangeException("type"); } CollaborationHelperFunctions.Initialize(); int errorCode = 0; // // Convert PeerApplication.Guid into native GUID struct // PEER_APPLICATION_REGISTRATION_INFO appRegInfo = new PEER_APPLICATION_REGISTRATION_INFO(); appRegInfo.application.guid = CollaborationHelperFunctions.ConvertGuidToGUID(application.Id); appRegInfo.pwzApplicationArguments = application.CommandLineArgs; appRegInfo.pwzApplicationToLaunch = application.Path; appRegInfo.dwPublicationScope = (uint)application.PeerScope; if (Logging.P2PTraceSource.Switch.ShouldTrace(TraceEventType.Information)){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RegisterApplication() is called with the following Info"); application.TracePeerApplication(); } unsafe{ SafeCollabMemory data = null; appRegInfo.application.data.cbData = (application.Data!=null) ? (UInt32)application.Data.Length : 0; GCHandle descHandle = new GCHandle(); try{ // // Marshal any data to send to native call // if ((application.Data!=null) && (application.Data.Length > 0)) { data = new SafeCollabMemory(application.Data.Length); appRegInfo.application.data.pbData = data.DangerousGetHandle(); Marshal.Copy(application.Data, 0, appRegInfo.application.data.pbData, application.Data.Length); } else appRegInfo.application.data.pbData = IntPtr.Zero; descHandle = GCHandle.Alloc(application.Description, GCHandleType.Pinned); appRegInfo.application.pwzDescription = descHandle.AddrOfPinnedObject(); errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterApplication(ref appRegInfo, type); } finally{ if (descHandle.IsAllocated) descHandle.Free(); if (data != null) data.Dispose(); } } if (errorCode == UnsafeCollabReturnCodes.PEER_E_ALREADY_EXISTS){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterApplication returned with errorcode {0}. Application already registered.", errorCode); throw new ArgumentException(SR.GetString(SR.Collab_AppRegFailed) + " " + SR.GetString(SR.Collab_AppExists)); } else if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterApplication returned with errorcode {0}", errorCode); throw (PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_AppRegFailed), errorCode)); } Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "RegisterApplication successful"); }
public void UnsafeLogEvent(TraceEventType type, ushort eventLogCategory, uint eventId, bool shouldTrace, params string[] values) { if (logCountForPT >= 5) { return; } try { int num = 0; string[] logValues = new string[values.Length + 2]; for (int i = 0; i < values.Length; i++) { string str = values[i]; if (!string.IsNullOrEmpty(str)) { str = NormalizeEventLogParameter(str); } else { str = string.Empty; } logValues[i] = str; num += str.Length + 1; } string str2 = NormalizeEventLogParameter(this.UnsafeGetProcessName()); logValues[logValues.Length - 2] = str2; num += str2.Length + 1; string str3 = this.UnsafeGetProcessId().ToString(CultureInfo.InvariantCulture); logValues[logValues.Length - 1] = str3; num += str3.Length + 1; if (num > 0x6400) { int length = (0x6400 / logValues.Length) - 1; for (int j = 0; j < logValues.Length; j++) { if (logValues[j].Length > length) { logValues[j] = logValues[j].Substring(0, length); } } } SecurityIdentifier user = WindowsIdentity.GetCurrent().User; byte[] binaryForm = new byte[user.BinaryLength]; user.GetBinaryForm(binaryForm, 0); IntPtr[] ptrArray = new IntPtr[logValues.Length]; GCHandle stringsRootHandle = new GCHandle(); GCHandle[] handleArray = null; try { stringsRootHandle = GCHandle.Alloc(ptrArray, GCHandleType.Pinned); handleArray = new GCHandle[logValues.Length]; for (int k = 0; k < logValues.Length; k++) { handleArray[k] = GCHandle.Alloc(logValues[k], GCHandleType.Pinned); ptrArray[k] = handleArray[k].AddrOfPinnedObject(); } this.UnsafeWriteEventLog(type, eventLogCategory, eventId, logValues, binaryForm, stringsRootHandle); } finally { if (stringsRootHandle.AddrOfPinnedObject() != IntPtr.Zero) { stringsRootHandle.Free(); } if (handleArray != null) { foreach (GCHandle handle2 in handleArray) { handle2.Free(); } } } if ((shouldTrace && (this.diagnosticTrace != null)) && ((TraceCore.TraceCodeEventLogCriticalIsEnabled(this.diagnosticTrace) || TraceCore.TraceCodeEventLogVerboseIsEnabled(this.diagnosticTrace)) || ((TraceCore.TraceCodeEventLogInfoIsEnabled(this.diagnosticTrace) || TraceCore.TraceCodeEventLogWarningIsEnabled(this.diagnosticTrace)) || TraceCore.TraceCodeEventLogErrorIsEnabled(this.diagnosticTrace)))) { Dictionary<string, string> dictionary = new Dictionary<string, string>(logValues.Length + 4); dictionary["CategoryID.Name"] = "EventLogCategory"; dictionary["CategoryID.Value"] = eventLogCategory.ToString(CultureInfo.InvariantCulture); dictionary["InstanceID.Name"] = "EventId"; dictionary["InstanceID.Value"] = eventId.ToString(CultureInfo.InvariantCulture); for (int m = 0; m < values.Length; m++) { dictionary.Add("Value" + m.ToString(CultureInfo.InvariantCulture), (values[m] == null) ? string.Empty : DiagnosticTrace.XmlEncode(values[m])); } TraceRecord traceRecord = new DictionaryTraceRecord(dictionary); switch (type) { case TraceEventType.Critical: TraceCore.TraceCodeEventLogCritical(this.diagnosticTrace, traceRecord); goto Label_035C; case TraceEventType.Error: TraceCore.TraceCodeEventLogError(this.diagnosticTrace, traceRecord); goto Label_035C; case (TraceEventType.Error | TraceEventType.Critical): goto Label_035C; case TraceEventType.Warning: TraceCore.TraceCodeEventLogWarning(this.diagnosticTrace, traceRecord); goto Label_035C; case TraceEventType.Information: TraceCore.TraceCodeEventLogInfo(this.diagnosticTrace, traceRecord); goto Label_035C; case TraceEventType.Verbose: TraceCore.TraceCodeEventLogVerbose(this.diagnosticTrace, traceRecord); goto Label_035C; } } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } } Label_035C: if (this.isInPartialTrust) { logCountForPT++; } }
/// <summary>Remove the memory allocated</summary> /// <param name="aGCHandle"></param> /// <param name="gchandleArgs"></param> private void ClearParameters(ref GCHandle[] aGCHandle, ref GCHandle gchandleArgs) { for (int intCounter = 0; intCounter < aGCHandle.Length; intCounter++) aGCHandle[intCounter].Free(); gchandleArgs.Free(); }
/// <summary> /// Protect /// </summary> public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) { if (userData == null) throw new ArgumentNullException("userData"); GCHandle pbDataIn = new GCHandle(); GCHandle pOptionalEntropy = new GCHandle(); CAPI.CRYPTOAPI_BLOB blob = new CAPI.CRYPTOAPI_BLOB(); try { pbDataIn = GCHandle.Alloc(userData, GCHandleType.Pinned); CAPI.CRYPTOAPI_BLOB dataIn = new CAPI.CRYPTOAPI_BLOB(); dataIn.cbData = (uint)userData.Length; dataIn.pbData = pbDataIn.AddrOfPinnedObject(); CAPI.CRYPTOAPI_BLOB entropy = new CAPI.CRYPTOAPI_BLOB(); if (optionalEntropy != null) { pOptionalEntropy = GCHandle.Alloc(optionalEntropy, GCHandleType.Pinned); entropy.cbData = (uint)optionalEntropy.Length; entropy.pbData = pOptionalEntropy.AddrOfPinnedObject(); } uint dwFlags = CAPI.CRYPTPROTECT_UI_FORBIDDEN; if (scope == DataProtectionScope.LocalMachine) dwFlags |= CAPI.CRYPTPROTECT_LOCAL_MACHINE; unsafe { if (!CAPI.CryptProtectData(new IntPtr(&dataIn), String.Empty, new IntPtr(&entropy), IntPtr.Zero, IntPtr.Zero, dwFlags, new IntPtr(&blob))) { int lastWin32Error = Marshal.GetLastWin32Error(); // One of the most common reasons that DPAPI operations fail is that the user // profile is not loaded (for instance in the case of impersonation or running in a // service. In those cases, throw an exception that provides more specific details // about what happened. if (CAPI.ErrorMayBeCausedByUnloadedProfile(lastWin32Error)) { throw new CryptographicException("Cryptography_DpApi_ProfileMayNotBeLoaded"); } else { throw new CryptographicException(lastWin32Error); } } } // In some cases, the API would fail due to OOM but simply return a null pointer. if (blob.pbData == IntPtr.Zero) throw new OutOfMemoryException(); byte[] encryptedData = new byte[(int)blob.cbData]; Marshal.Copy(blob.pbData, encryptedData, 0, encryptedData.Length); return encryptedData; } finally { if (pbDataIn.IsAllocated) pbDataIn.Free(); if (pOptionalEntropy.IsAllocated) pOptionalEntropy.Free(); if (blob.pbData != IntPtr.Zero) { CAPI.ZeroMemory(blob.pbData, blob.cbData); CAPI.LocalFree(blob.pbData); } } }
private async void StartRequest(object obj) { RequestState state = (RequestState)obj; bool secureConnection = false; HttpResponseMessage responseMessage = null; Exception savedException = null; SafeWinHttpHandle connectHandle = null; SafeWinHttpHandle requestHandle = null; GCHandle requestStateHandle = new GCHandle(); if (state.CancellationToken.IsCancellationRequested) { state.Tcs.TrySetCanceled(state.CancellationToken); return; } try { // Prepare context object. requestStateHandle = GCHandle.Alloc(state); EnsureSessionHandleExists(state); SetSessionHandleOptions(); // Specify an HTTP server. connectHandle = Interop.WinHttp.WinHttpConnect( _sessionHandle, state.RequestMessage.RequestUri.Host, (ushort)state.RequestMessage.RequestUri.Port, 0); if (connectHandle.IsInvalid) { throw new HttpRequestException( SR.net_http_client_execution_error, WinHttpException.CreateExceptionUsingLastError()); } connectHandle.SetParentHandle(_sessionHandle); if (state.RequestMessage.RequestUri.Scheme == UriSchemeHttps) { secureConnection = true; } else { secureConnection = false; } // Create an HTTP request handle. requestHandle = Interop.WinHttp.WinHttpOpenRequest( connectHandle, state.RequestMessage.Method.Method, state.RequestMessage.RequestUri.PathAndQuery, null, Interop.WinHttp.WINHTTP_NO_REFERER, Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES, secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0); if (requestHandle.IsInvalid) { throw new HttpRequestException( SR.net_http_client_execution_error, WinHttpException.CreateExceptionUsingLastError()); } requestHandle.SetParentHandle(connectHandle); state.RequestHandle = requestHandle; // Set callback function. SetStatusCallback(requestHandle, s_staticCallback); // Set needed options on the request handle. SetRequestHandleOptions(state); bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage); AddRequestHeaders( requestHandle, state.RequestMessage, _cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null); uint proxyAuthScheme = 0; uint serverAuthScheme = 0; bool retryRequest = false; do { state.CancellationToken.ThrowIfCancellationRequested(); PreAuthenticateRequest(state, requestHandle, proxyAuthScheme); // Send a request. if (!Interop.WinHttp.WinHttpSendRequest( requestHandle, null, 0, IntPtr.Zero, 0, 0, GCHandle.ToIntPtr(requestStateHandle))) { WinHttpException.ThrowExceptionUsingLastError(); } // Send request body if present. if (state.RequestMessage.Content != null) { using (var requestStream = new WinHttpRequestStream(requestHandle, chunkedModeForSend)) { await state.RequestMessage.Content.CopyToAsync( requestStream, state.TransportContext).ConfigureAwait(false); requestStream.EndUpload(); } } state.CancellationToken.ThrowIfCancellationRequested(); // End the request and wait for the response. if (!Interop.WinHttp.WinHttpReceiveResponse(requestHandle, IntPtr.Zero)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == (int)Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST) { retryRequest = true; } else if (lastError == (int)Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) { // WinHttp will automatically drop any client SSL certificates that we // have pre-set into the request handle. For security reasons, we don't // allow the certificate to be re-applied. But we need to tell WinHttp // that we don't have any certificate. SetNoClientCertificate(requestHandle); retryRequest = true; } else { throw WinHttpException.CreateExceptionUsingError(lastError); } } else { ProcessResponse( state, requestHandle, ref proxyAuthScheme, ref serverAuthScheme, out retryRequest); } } while (retryRequest); // Clear callback function in WinHTTP once we have a final response // and are ready to create the response message. SetStatusCallback(requestHandle, null); state.CancellationToken.ThrowIfCancellationRequested(); // Create HttpResponseMessage object. responseMessage = CreateResponseMessage(requestHandle, state.RequestMessage); } catch (Exception ex) { if (ex is OperationCanceledException) { savedException = ex; } else if (state.SavedException != null) { savedException = state.SavedException; } else { savedException = ex; } // Clear callback function in WinHTTP to prevent // further native callbacks as we clean up the objects. if (requestHandle != null) { SetStatusCallback(requestHandle, null); } } if (requestStateHandle.IsAllocated) { requestStateHandle.Free(); } SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle); // Move the task to a terminal state. if (responseMessage != null) { state.Tcs.TrySetResult(responseMessage); } else { HandleAsyncException(state, savedException); } }
/// <summary> /// Read the image file into a Tensorflow tensor /// </summary> /// <typeparam name="T">The tensor data type, e.g. float</typeparam> /// <param name="fileName">The name of the image file</param> /// <param name="inputHeight">The height of the input tensor. If zero or negative, will use the image height from the file</param> /// <param name="inputWidth">The width of the input tensor. If zero or negative, will use the image width from the file</param> /// <param name="inputMean">The input mean, will be subtracted from the image pixel value</param> /// <param name="scale">The optional scale, after input means is substracted, the pixel value will multiply with the scale to produce the tensor value</param> /// <param name="flipUpSideDown">If true, the image will be flipped upside down</param> /// <param name="swapBR">If true, the blue and red channels will be swapped</param> /// <returns>The tensorflow tensor.</returns> public static Tensor ReadTensorFromImageFile <T>( String fileName, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { #if __ANDROID__ return(NativeReadTensorFromImageFile <T>(fileName, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, swapBR)); #elif __IOS__ UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)image.Size.Height, (int)image.Size.Width, 3 }); System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length); return(t); #else FileInfo fi = new FileInfo(fileName); String extension = fi.Extension.ToLower(); //Use tensorflow to decode the following image formats if ((typeof(T) == typeof(float)) && (extension.Equals(".jpeg") || extension.Equals(".jpg") || extension.Equals(".png") || extension.Equals(".gif"))) { return(DecodeImageToTensor32F3C(fileName, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, swapBR)); } else { return(NativeReadTensorFromImageFile <T>(fileName, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, swapBR)); } #endif }