private Mogre.Image SystemtoMogreImage(System.Drawing.Image image) { Stream oStream = new MemoryStream(); image.Save(oStream, System.Drawing.Imaging.ImageFormat.Png); /* Back to the start of the stream */ oStream.Position = 0; /* read all the stream in a buffer */ BinaryReader oBinaryReader = new BinaryReader(oStream); byte[] pBuffer = oBinaryReader.ReadBytes((int)oBinaryReader.BaseStream.Length); oStream.Close(); /*No more needed */ Mogre.Image oMogreImage = new Mogre.Image(); unsafe { System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(pBuffer, System.Runtime.InteropServices.GCHandleType.Pinned); byte *pUnsafeByte = (byte *)handle.AddrOfPinnedObject(); void *pUnsafeBuffer = (void *)handle.AddrOfPinnedObject(); MemoryDataStream oMemoryStream = new MemoryDataStream(pUnsafeBuffer, (uint)pBuffer.Length); DataStreamPtr oPtrDataStream = new DataStreamPtr(oMemoryStream); oMogreImage = oMogreImage.Load(oPtrDataStream, "png"); handle.Free(); } return(oMogreImage); }
public TextureContent(GraphicsDevice graphicsDevice, bool generateMipMaps, int mipMapCount, byte[] inputData, int width, int height, TextureContentFormat inputFormat, TextureContentFormat outputFormat) { this.graphicsDevice = graphicsDevice; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(inputData, System.Runtime.InteropServices.GCHandleType.Pinned); createTexture(generateMipMaps, mipMapCount, handle.AddrOfPinnedObject(), width, height, inputFormat, outputFormat); handle.Free(); }
public override void SetData <T>(T[] data, int startIndex, int elementCount) { if (_usage == VertexBufferUsage.Static) { throw new Exception("Can't update a vertex buffer created as Static"); } GL.GetError(); GL.BindBuffer(BufferTarget.ArrayBuffer, _buffer); System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { IntPtr pointer = handle.AddrOfPinnedObject(); int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(elementCount * size), Gk3Main.Utils.IncrementIntPtr(pointer, size * startIndex), (BufferUsageHint)convertUsage(_usage)); } finally { if (handle.IsAllocated) { handle.Free(); } } GlException.ThrowExceptionIfErrorExists(); }
private string GetMemory(object obj) { System.Runtime.InteropServices.GCHandle h = System.Runtime.InteropServices.GCHandle.Alloc(obj, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr addr = h.AddrOfPinnedObject(); return(addr.ToString("X")); }
public unsafe static T[] Create <T>(void *source, int length) { System.Type type = typeof(T); int sizeInBytes = System.Runtime.InteropServices.Marshal.SizeOf(type); T[] output = new T[length]; if (type.IsPrimitive) { // Make sure the array won't be moved around by the GC System.Runtime.InteropServices.GCHandle handleOutput = default(System.Runtime.InteropServices.GCHandle); try { handleOutput = System.Runtime.InteropServices.GCHandle.Alloc(output, System.Runtime.InteropServices.GCHandleType.Pinned); int byteLength = length * sizeInBytes; // There are faster ways to do this, particularly by using wider types or by // handling special lengths. //for (int i = 0; i < byteLength; i++) // destination[i] = ((byte*)source)[i]; //E,g, like this... the problem is that handle doesn't point to the array elements... //Could instead give a T[] source or IntPtr. System.Buffer.MemoryCopy(source, (void *)handleOutput.AddrOfPinnedObject(), byteLength, byteLength); } finally { if (handleOutput.IsAllocated) { handleOutput.Free(); } } } else if (type.IsValueType) { if (false == type.IsLayoutSequential && false == type.IsExplicitLayout) { throw new System.InvalidOperationException(string.Format("{0} does not define a StructLayout attribute", type)); } System.IntPtr sourcePtr = new System.IntPtr(source); for (int i = 0; i < length; i++) { System.IntPtr p = new System.IntPtr((byte *)source + i * sizeInBytes); output[i] = (T)System.Runtime.InteropServices.Marshal.PtrToStructure(p, typeof(T)); } } else { throw new System.InvalidOperationException(string.Format("{0} is not supported", type)); } return(output); }
/// <summary> /// 获取字符串的地址位 /// </summary> /// <param name="e"></param> /// <returns></returns> int VarPtr(object e) { System.Runtime.InteropServices.GCHandle gh = System.Runtime.InteropServices.GCHandle.Alloc(e, System.Runtime.InteropServices.GCHandleType.Pinned); int gc = gh.AddrOfPinnedObject().ToInt32(); gh.Free(); return(gc); }
/// <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(); }
public IntPtr PinData() { if (m_PinnedHandle != default(System.Runtime.InteropServices.GCHandle)) { return(m_PinnedHandle.AddrOfPinnedObject()); } m_PinnedHandle = System.Runtime.InteropServices.GCHandle.Alloc(m_Data, System.Runtime.InteropServices.GCHandleType.Pinned); return(m_PinnedHandle.AddrOfPinnedObject()); }
private void FormDebugging_Load(object sender, EventArgs e) { frmWhiteBoard = new FormWhiteBoard(); frmWhiteBoard.Show(); byte x; x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT);// x is 1 GL.Disable(GL.GL_DEBUG_OUTPUT); x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT);// x is 0 GL.Enable(GL.GL_DEBUG_OUTPUT); x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT); // x is 1 x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); // x is 0 GL.Disable(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);// x is 0 GL.Enable(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);// x is 1 // 必须是struct UserParamStruct data = new UserParamStruct() { integer = 123, handle = this.glCanvas1.Handle }; this.userParamInstance = System.Runtime.InteropServices.GCHandle.Alloc( data, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr ptr = userParamInstance.AddrOfPinnedObject(); GL.DebugMessageCallback(this.callbackProc, ptr); GL.DebugMessageControl( Enumerations.DebugMessageControlSource.DONT_CARE, Enumerations.DebugMessageControlType.DONT_CARE, Enumerations.DebugMessageControlSeverity.DONT_CARE, 0, null, true); StringBuilder builder = new StringBuilder(); builder.Append("hello, this is app!"); GL.DebugMessageInsert( Enumerations.DebugSource.DEBUG_SOURCE_APPLICATION_ARB, Enumerations.DebugType.DEBUG_TYPE_OTHER_ARB, 0x4752415A, //Enumerations.DebugSeverity.DEBUG_SEVERITY_NOTIFICATION_ARB,// not valid Enumerations.DebugSeverity.DEBUG_SEVERITY_HIGH_ARB, //Enumerations.DebugSeverity.DEBUG_SEVERITY_MEDIUM_ARB, //Enumerations.DebugSeverity.DEBUG_SEVERITY_LOW_ARB, -1, builder); }
public Font UseMemoryFont(float size) { System.Runtime.InteropServices.GCHandle hObject = System.Runtime.InteropServices.GCHandle.Alloc(Properties.Resources.iconfont, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr intptr = hObject.AddrOfPinnedObject(); PrivateFontCollection fc = new PrivateFontCollection(); fc.AddMemoryFont(intptr, Properties.Resources.iconfont.Length); Font font = new Font(fc.Families[0], size, FontStyle.Regular, GraphicsUnit.Point, 0); return(font); }
private System.Collections.IEnumerator LoadFile() { ms_www = new UnityEngine.WWW(m_bankPath); yield return(ms_www); uint in_uInMemoryBankSize = 0; // Allocate an aligned buffer try { ms_pinnedArray = System.Runtime.InteropServices.GCHandle.Alloc(ms_www.bytes, System.Runtime.InteropServices.GCHandleType.Pinned); ms_pInMemoryBankPtr = ms_pinnedArray.AddrOfPinnedObject(); in_uInMemoryBankSize = (uint)ms_www.bytes.Length; // Array inside the WWW object is not aligned. Allocate a new array for which we can guarantee the alignment. if ((ms_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0) { var alignedBytes = new byte[ms_www.bytes.Length + AK_BANK_PLATFORM_DATA_ALIGNMENT]; var new_pinnedArray = System.Runtime.InteropServices.GCHandle.Alloc(alignedBytes, System.Runtime.InteropServices.GCHandleType.Pinned); var new_pInMemoryBankPtr = new_pinnedArray.AddrOfPinnedObject(); var alignedOffset = 0; // New array is not aligned, so we will need to use an offset inside it to align our data. if ((new_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0) { var alignedPtr = (new_pInMemoryBankPtr.ToInt64() + AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) & ~AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK; alignedOffset = (int)(alignedPtr - new_pInMemoryBankPtr.ToInt64()); new_pInMemoryBankPtr = new System.IntPtr(alignedPtr); } // Copy the bank's bytes in our new array, at the correct aligned offset. System.Array.Copy(ms_www.bytes, 0, alignedBytes, alignedOffset, ms_www.bytes.Length); ms_pInMemoryBankPtr = new_pInMemoryBankPtr; ms_pinnedArray.Free(); ms_pinnedArray = new_pinnedArray; } } catch { yield break; } var result = AkSoundEngine.LoadBank(ms_pInMemoryBankPtr, in_uInMemoryBankSize, out ms_bankID); if (result != AKRESULT.AK_Success) { UnityEngine.Debug.LogError("WwiseUnity: AkMemBankLoader: bank loading failed with result " + result); } }
private void getFileInfo(string myFile) { //Initilaizing MediaInfo MediaInfo MI = new MediaInfo(); //From: preparing an example file for reading FileStream From = new FileStream(myFile, FileMode.Open, FileAccess.Read); //From: preparing a memory buffer for reading byte[] From_Buffer = new byte[64 * 1024]; int From_Buffer_Size; //The size of the read file buffer //Preparing to fill MediaInfo with a buffer MI.Open_Buffer_Init(From.Length, 0); //The parsing loop do { //Reading data somewhere, do what you want for this. From_Buffer_Size = From.Read(From_Buffer, 0, 64 * 1024); //Sending the buffer to MediaInfo System.Runtime.InteropServices.GCHandle GC = System.Runtime.InteropServices.GCHandle.Alloc(From_Buffer, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr From_Buffer_IntPtr = GC.AddrOfPinnedObject(); Status Result = (Status)MI.Open_Buffer_Continue(From_Buffer_IntPtr, (IntPtr)From_Buffer_Size); GC.Free(); if ((Result & Status.Finalized) == Status.Finalized) { break; } //Testing if MediaInfo request to go elsewhere if (MI.Open_Buffer_Continue_GoTo_Get() != -1) { Int64 Position = From.Seek(MI.Open_Buffer_Continue_GoTo_Get(), SeekOrigin.Begin); //Position the file MI.Open_Buffer_Init(From.Length, Position); //Informing MediaInfo we have seek } }while (From_Buffer_Size > 0); //Finalizing MI.Open_Buffer_Finalize(); //This is the end of the stream, MediaInfo must finnish some work //Get() example string itemWidth = MI.Get(StreamKind.Video, 0, "Width"); string itemHeight = MI.Get(StreamKind.Video, 0, "Height"); string itemFormat = MI.Get(StreamKind.Video, 0, "Format"); string itemAudFormat = MI.Get(StreamKind.Audio, 0, "Format"); string itemAudChans = MI.Get(StreamKind.Audio, 0, "Channels"); string myOutpt = itemWidth + "\r\n" + itemHeight + "\r\n" + itemFormat + "\r\n" + itemAudFormat + "\r\n" + itemAudChans + "\r\n";; richTextBox1.Text = myOutpt; }
private void TrySetMediaInfo(string filePath) { try { MI = new MediaInfoLib.MediaInfo(); #region Media Info Init FileStream From = new FileStream(filePath, FileMode.Open, FileAccess.Read); //From: preparing a memory buffer for reading byte[] From_Buffer = new byte[64 * 1024]; int From_Buffer_Size; //The size of the read file buffer //Preparing to fill MediaInfo with a buffer MI.Open_Buffer_Init(From.Length, 0); //The parsing loop do { //Reading data somewhere, do what you want for this. From_Buffer_Size = From.Read(From_Buffer, 0, 64 * 1024); //Sending the buffer to MediaInfo System.Runtime.InteropServices.GCHandle GC = System.Runtime.InteropServices.GCHandle.Alloc(From_Buffer, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr From_Buffer_IntPtr = GC.AddrOfPinnedObject(); Status Result = (Status)MI.Open_Buffer_Continue(From_Buffer_IntPtr, (IntPtr)From_Buffer_Size); GC.Free(); if ((Result & Status.Finalized) == Status.Finalized) { break; } //Testing if MediaInfo request to go elsewhere if (MI.Open_Buffer_Continue_GoTo_Get() != -1) { Int64 Position = From.Seek(MI.Open_Buffer_Continue_GoTo_Get(), SeekOrigin.Begin); //Position the file MI.Open_Buffer_Init(From.Length, Position); //Informing MediaInfo we have seek } }while (From_Buffer_Size > 0); //Finalizing MI.Open_Buffer_Finalize(); //This is the end of the stream, MediaInfo must finnish some work #endregion } catch (Exception ex) { var c = ex.Message; } }
ArrayMakeSerializer_Struct(Type Type, int size) { if (Type.GetElementType() == typeof(bool)) { size = 1; } Action <SerializeData, System.Array> Serializer = (Data, ar) => { byte[] bytes = new byte[ar.Length * size]; System.Runtime.InteropServices.GCHandle h = System.Runtime.InteropServices.GCHandle.Alloc(ar, System.Runtime.InteropServices.GCHandleType.Pinned); var ptr = h.AddrOfPinnedObject(); System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, bytes.Length); h.Free(); Data.S_Data.Write(bytes, 0, bytes.Length); }; Action <DeserializeData, (System.Array ar, int[] Ends)> Deserializer = (Data, obj) => { var ar = obj.ar; var Ends = obj.Ends; var Rank = Ends.Length; var Len = 0; Len = Ends[0]; for (int i = 1; i < Rank; i++) { Len = Len * Ends[i]; } Len = Len * size; System.Runtime.InteropServices.GCHandle h = System.Runtime.InteropServices.GCHandle.Alloc(ar, System.Runtime.InteropServices.GCHandleType.Pinned); var ptr = h.AddrOfPinnedObject(); System.Runtime.InteropServices.Marshal.Copy(Data.D_Data, Data.From, ptr, Len); h.Free(); Data.From += Len; }; return(Serializer, Deserializer); }
String ExampleWithStream() { //Initilaizing MediaInfo MediaInfo MI = new MediaInfo(); //From: preparing an example file for reading FileStream From = new FileStream("Example.ogg", FileMode.Open, FileAccess.Read); //From: preparing a memory buffer for reading byte[] From_Buffer = new byte[64 * 1024]; int From_Buffer_Size; //The size of the read file buffer //Preparing to fill MediaInfo with a buffer MI.Open_Buffer_Init(From.Length, 0); //The parsing loop do { //Reading data somewhere, do what you want for this. From_Buffer_Size = From.Read(From_Buffer, 0, 64 * 1024); //Sending the buffer to MediaInfo System.Runtime.InteropServices.GCHandle GC = System.Runtime.InteropServices.GCHandle.Alloc(From_Buffer, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr From_Buffer_IntPtr = GC.AddrOfPinnedObject(); Status Result = (Status)MI.Open_Buffer_Continue(From_Buffer_IntPtr, (IntPtr)From_Buffer_Size); GC.Free(); if ((Result & Status.Finalized) == Status.Finalized) { break; } //Testing if MediaInfo request to go elsewhere if (MI.Open_Buffer_Continue_GoTo_Get() != -1) { Int64 Position = From.Seek(MI.Open_Buffer_Continue_GoTo_Get(), SeekOrigin.Begin); //Position the file MI.Open_Buffer_Init(From.Length, Position); //Informing MediaInfo we have seek } }while (From_Buffer_Size > 0); //Finalizing MI.Open_Buffer_Finalize(); //This is the end of the stream, MediaInfo must finnish some work //Get() example return("Container format is " + MI.Get(StreamKind.General, 0, "Format")); }
/// <summary> /// Create the collision height map. /// </summary> /// <param name="heightData">Height map data (should be defined as byte[size.X * size.Y * 4]).</param> /// <param name="size">Tilemap size (Y is actually Z axis).</param> /// <param name="scale">Scale tiles width and depth.</param> /// <param name="minHeight">Min height value.</param> /// <param name="maxHeight">Max height value.</param> /// <param name="heightScale">Optional height scale.</param> /// <param name="upIndex">Up index.</param> /// <param name="useDiamondSubdivision">Divide the tiles into diamond shapes for more accurare results.</param> private void Build(float[] heightData, Point size, Vector2 scale, float minHeight = 0f, float maxHeight = 100f, float heightScale = 1f, int upIndex = 1, bool useDiamondSubdivision = false) { // get int ptr for data bytes _rawDataHandle = System.Runtime.InteropServices.GCHandle.Alloc(heightData, System.Runtime.InteropServices.GCHandleType.Pinned); var address = _rawDataHandle.AddrOfPinnedObject(); // create heightmap var heightmap = new BulletSharp.HeightfieldTerrainShape(size.X, size.Y, address, heightScale, minHeight, maxHeight, upIndex, BulletSharp.PhyScalarType.Single, false); // set transform and diamond subdivision heightmap.SetUseDiamondSubdivision(useDiamondSubdivision); heightmap.LocalScaling = ToBullet.Vector(new Vector3(scale.X, 1, scale.Y)); // set shape _shape = heightmap; }
private uint AllocateAlignedBuffer(byte[] data) { uint uInMemoryBankSize = 0; // Allocate an aligned buffer try { ms_pinnedArray = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); ms_pInMemoryBankPtr = ms_pinnedArray.AddrOfPinnedObject(); uInMemoryBankSize = (uint)data.Length; // Array inside the WWW object is not aligned. Allocate a new array for which we can guarantee the alignment. if ((ms_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0) { var alignedBytes = new byte[data.Length + AK_BANK_PLATFORM_DATA_ALIGNMENT]; var new_pinnedArray = System.Runtime.InteropServices.GCHandle.Alloc(alignedBytes, System.Runtime.InteropServices.GCHandleType.Pinned); var new_pInMemoryBankPtr = new_pinnedArray.AddrOfPinnedObject(); var alignedOffset = 0; // New array is not aligned, so we will need to use an offset inside it to align our data. if ((new_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0) { var alignedPtr = (new_pInMemoryBankPtr.ToInt64() + AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) & ~AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK; alignedOffset = (int)(alignedPtr - new_pInMemoryBankPtr.ToInt64()); new_pInMemoryBankPtr = new System.IntPtr(alignedPtr); } // Copy the bank's bytes in our new array, at the correct aligned offset. System.Array.Copy(data, 0, alignedBytes, alignedOffset, data.Length); ms_pInMemoryBankPtr = new_pInMemoryBankPtr; ms_pinnedArray.Free(); ms_pinnedArray = new_pinnedArray; } } catch { } return(uInMemoryBankSize); }
static void Main() { string variableName = "CSHARP-UEFI"; string GUID = "{E660597E-B94D-4209-9C80-1805B5D19B69}"; int error = 0; bool pass = false; IntPtr bufferPRE = IntPtr.Zero; bool ret = pinvoke.SetPriv(); System.Runtime.InteropServices.GCHandle pinnedArray = System.Runtime.InteropServices.GCHandle.Alloc(buf.buffer, System.Runtime.InteropServices.GCHandleType.Pinned); bufferPRE = pinnedArray.AddrOfPinnedObject(); pass = pinvoke.SetFirmwareEnvironmentVariableEx(variableName, GUID, bufferPRE, (uint)buf.buffer.Length, (uint)pinvoke.dwAttributes.VARIABLE_ATTRIBUTE_NON_VOLATILE); if (!pass) { error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); } pinnedArray.Free(); }
public T[] ReadArraySync <T>(ulong pointer, ulong size) where T : struct { ulong typeSize = (ulong)System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); ulong byteSize = size * typeSize; byte[] memory = this.ReadByteArray(pointer, byteSize); T[] result = new T[size]; System.Runtime.InteropServices.GCHandle gcHandle = System.Runtime.InteropServices.GCHandle.Alloc(result, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr tPointer = gcHandle.AddrOfPinnedObject(); for (ulong i = 0; i < byteSize; i++) { System.Runtime.InteropServices.Marshal.WriteByte(tPointer, memory[i]); // move tPointer by 1 byte. tPointer = IntPtr.Add(tPointer, 1); } gcHandle.Free(); return(result); }
public static void TestCapture() { Foundation.NSNumber mainScreen = (Foundation.NSNumber)AppKit.NSScreen.MainScreen.DeviceDescription["NSScreenNumber"]; using (CoreGraphics.CGImage cgImage = CreateImage(mainScreen.UInt32Value)) { // https://stackoverflow.com/questions/17334786/get-pixel-from-the-screen-screenshot-in-max-osx/17343305#17343305 // Get byte-array from CGImage // https://gist.github.com/zhangao0086/5fafb1e1c0b5d629eb76 AppKit.NSBitmapImageRep bitmapRep = new AppKit.NSBitmapImageRep(cgImage); // var imageData = bitmapRep.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:]) Foundation.NSData imageData = bitmapRep.RepresentationUsingTypeProperties(AppKit.NSBitmapImageFileType.Png); long len = imageData.Length; byte[] bytes = new byte[len]; System.Runtime.InteropServices.GCHandle pinnedArray = System.Runtime.InteropServices.GCHandle.Alloc(bytes, System.Runtime.InteropServices.GCHandleType.Pinned); System.IntPtr pointer = pinnedArray.AddrOfPinnedObject(); // Do your stuff... imageData.GetBytes(pointer, new System.IntPtr(len)); pinnedArray.Free(); using (AppKit.NSImage nsImage = new AppKit.NSImage(cgImage, new System.Drawing.SizeF(cgImage.Width, cgImage.Height))) { // ImageView.Image = nsImage; // And now ? How to get the image bytes ? // https://theconfuzedsourcecode.wordpress.com/2016/02/24/convert-android-bitmap-image-and-ios-uiimage-to-byte-array-in-xamarin/ // https://stackoverflow.com/questions/5645157/nsimage-from-byte-array // https://stackoverflow.com/questions/53060723/nsimage-source-from-byte-array-cocoa-app-xamarin-c-sharp // https://gist.github.com/zhangao0086/5fafb1e1c0b5d629eb76 // https://www.quora.com/What-is-a-way-to-convert-UIImage-to-a-byte-array-in-Swift?share=1 // https://stackoverflow.com/questions/17112314/converting-uiimage-to-byte-array } // End Using nsImage } // End Using cgImage } // End Sub TestCapture
private static void TryThat() { string DEFAULTDIRECTORY = "C:\\Users\\Zachary Burns\\Desktop\\TEMPDIR"; System.IO.FileStream fs = System.IO.File.OpenRead(DEFAULTDIRECTORY + "\\test.mp3"); int length = (int)fs.Length; byte[] buffer = new byte[length]; fs.Read(buffer, 0, length); fs.Close(); Un4seen.Bass.BassNet.Registration("*****@*****.**", "2X113281839322"); Un4seen.Bass.BassNet.OmitCheckVersion = true; if (Un4seen.Bass.Bass.BASS_Init(-1, 44100, Un4seen.Bass.BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero)) { System.Runtime.InteropServices.GCHandle gch = System.Runtime.InteropServices.GCHandle.Alloc(buffer, System.Runtime.InteropServices.GCHandleType.Pinned); int stream = Un4seen.Bass.Bass.BASS_StreamCreateFile(gch.AddrOfPinnedObject(), 0L, buffer.Length, Un4seen.Bass.BASSFlag.BASS_SAMPLE_FLOAT); Un4seen.Bass.AddOn.Enc.BassEnc.BASS_Encode_Start(stream, DEFAULTDIRECTORY + "\\test" + ".wav", Un4seen.Bass.AddOn.Enc.BASSEncode.BASS_ENCODE_PCM, null, IntPtr.Zero); Un4seen.Bass.Bass.BASS_ChannelPlay(stream, false); Un4seen.Bass.Bass.BASS_StreamFree(stream); Un4seen.Bass.Bass.BASS_Free(); gch.Free(); } }
static Util() { HexConvHandle = System.Runtime.InteropServices.GCHandle.Alloc(HexConvArr, System.Runtime.InteropServices.GCHandleType.Pinned); HexConvPtr = (char *)HexConvHandle.AddrOfPinnedObject().ToPointer(); }
public static void CalibrateImage(WVConversionSettings conversionSettings) { string inputFilename = conversionSettings.inputNITFFilename; string inputIMDFilename = conversionSettings.inputIMDTarFilename; string outputFilename = conversionSettings.outputFilename; string outputHeaderFilename = outputFilename + ".hdr"; DataType outputType = conversionSettings.outputType; double scaleFactor = conversionSettings.scaleFactor; //open the input file Dataset ds = Gdal.Open(inputFilename, Access.GA_ReadOnly); if (ds == null) { throw new Exception("Can't open " + inputFilename); //stop if file could not be opened properly } //get GDAL driver for this file type Driver drv = ds.GetDriver(); if (drv == null) { throw new Exception("Can't get driver for reading."); //stop if driver could not be found for this file } //get image raster info // GDAL reads image in blocks, so get their size & how many int width = ds.RasterXSize; int height = ds.RasterYSize; int nBands = ds.RasterCount; int blockXSize, blockYSize; ds.GetRasterBand(1).GetBlockSize(out blockXSize, out blockYSize); int nImageXBlocks = (int)Math.Ceiling((double)width / blockXSize); int nImageYBlocks = (int)Math.Ceiling((double)height / blockYSize); DataType inputDataType = ds.GetRasterBand(1).DataType; int bytesPerSample = getBytesInSampleType(inputDataType); //note on cache size // default cache size is ~41MB // read buffer must be less than cache size for improved speed // appears that gdal can read images using multi-threading with 1 core decoding each block. // This works well as long as all currently needed blocks fit within the cache. // all bands for a block appear to be decoded at once // reading by block appears better because if we barely overrun the GDAL cache size the time doubles, // whereas if reading by row all blocks intersecting the row must be read every time a row is read (far slower) //set GDAL cache to encompass one row of image blocks for all bands (plus a little extra) OSGeo.GDAL.Gdal.SetCacheMax(nImageXBlocks * blockXSize * blockYSize * nBands * bytesPerSample + 50000000); //parse band info from IMD file string IMDTarFilename = inputIMDFilename; string[] IMDLines; if (IMDTarFilename.Substring(IMDTarFilename.Length - 4, 4).ToLower().Equals(".imd")) { IMDLines = File.ReadAllLines(IMDTarFilename); } else { IMDLines = Regex.Split(TarFileExtraction.getIMDFromTar(IMDTarFilename), "\r\n|\r|\n"); } BandInfo[] bandInfos = parseBandInfoFromIMD(IMDLines); //fine-tuning calibration info double[] fineTuneGains = new double[bandInfos.Length]; double[] fineTuneOffsets = new double[bandInfos.Length]; //set default values to make no changes for (int i = 0; i < bandInfos.Length; i++) { fineTuneGains[i] = 1; } //get fine-tune info if specified if (conversionSettings.applyFineTuningCal == true) { getFineTuneFactors(bandInfos, fineTuneGains, fineTuneOffsets); } //create new envi header file createENVIHeader(outputHeaderFilename, inputFilename, ds, bandInfos, outputType, scaleFactor); BinaryWriter bw = new BinaryWriter(new FileStream(outputFilename, FileMode.Create)); //report start of work if (conversionSettings.worker != null) { conversionSettings.worker.ReportProgress(0); } //convert images one row of blocks at a time int bytesPerOutputSample = getBytesInSampleType(outputType); for (int ys = 0; ys < nImageYBlocks; ys++) { //allocate buffer to store one band of data for one block row int rowHeight = (ys < nImageYBlocks - 1) ? blockYSize : (height - ys * blockYSize); byte[] inputBuffer = new byte[width * rowHeight * bytesPerSample]; double[][] dBuffer = new double[rowHeight][]; byte[] outputBuffer = new byte[width * rowHeight * bytesPerOutputSample]; for (int band = 1; band <= nBands; band++) { //read data System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(inputBuffer, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr pointer = handle.AddrOfPinnedObject(); ds.GetRasterBand(band).ReadRaster(0, ys * blockYSize, width, rowHeight, pointer, width, rowHeight, ds.GetRasterBand(1).DataType, 0, 0); handle.Free(); //convert raw input data to double precision for (int y = 0; y < rowHeight; y++) { dBuffer[y] = new double[width]; } convertByteArrayToDouble2D(dBuffer, inputBuffer, inputDataType); //calibrate for (int y = 0; y < rowHeight; y++) { for (int x = 0; x < width; x++) { dBuffer[y][x] = (fineTuneGains[band - 1] * dBuffer[y][x] * (bandInfos[band - 1].absCalFactor / bandInfos[band - 1].effectiveBandwidth) + fineTuneOffsets[band - 1]) / 10 * scaleFactor; } } //convert calibrated info to output data type convertDouble2DToByteArray(dBuffer, outputBuffer, outputType); //save calibrated data to output file long bToIndex = ((long)(band - 1) * width * height + ys * blockYSize * width + 0) * bytesPerOutputSample; bw.Flush(); bw.BaseStream.Seek(bToIndex, SeekOrigin.Begin); bw.Write(outputBuffer); //stop processing if work cancelled if (conversionSettings.worker != null && conversionSettings.worker.CancellationPending == true) { //stop writing to the file bw.Close(); //try to delete incomplete output files File.Delete(outputFilename); File.Delete(outputHeaderFilename); //stop processing return; } //report progress if (conversionSettings.worker != null) { conversionSettings.worker.ReportProgress((int)(((double)ys * nBands + band - 1 + 1) / (nImageYBlocks * nBands) * 100)); } } } //close output file bw.Close(); }
public int PlayFile(ISoundFile file, int fadeInTime, PlayingFinished callback, bool loop) { int channel = 0; BASSFlag speakerFlag = GetSpeakerFlag(file); BASSFlag decodeFlag = BASSFlag.BASS_STREAM_DECODE; if (file.SoundFileType == SoundFileType.Music && file.Effects.SpeakerAssignment.Active) { switch (file.Effects.SpeakerAssignment.Assignment) { case Data.SpeakerAssignment.AllSpeakers: case Data.SpeakerAssignment.BothCenterRears: case Data.SpeakerAssignment.BothFronts: case Data.SpeakerAssignment.BothRears: case Data.SpeakerAssignment.CenterAndSubwoofer: case Data.SpeakerAssignment.Default: break; default: decodeFlag |= BASSFlag.BASS_SAMPLE_MONO; break; } } #if MONO System.Runtime.InteropServices.GCHandle gcHandle = new System.Runtime.InteropServices.GCHandle(); #endif if (file.SoundFileType == SoundFileType.WebRadio) { channel = Bass.BASS_StreamCreateURL(file.Path, 0, decodeFlag | BASSFlag.BASS_STREAM_BLOCK, null, IntPtr.Zero); } else { #if MONO byte[] buffer = null; long length = 0; try { #if ANDROID if (file.Path.IsSmbFile()) { buffer = SambaHelpers.GetFileContent(file.Path); length = buffer.Length; } else { #endif System.IO.FileStream fs = System.IO.File.OpenRead(file.Path); length = fs.Length; buffer = new byte[length]; fs.Read(buffer, 0, (int)length); fs.Close(); #if ANDROID } #endif } catch (System.IO.IOException e) { ErrorHandling.ErrorOccurred(file.Id, e.Message); return(0); } gcHandle = System.Runtime.InteropServices.GCHandle.Alloc(buffer, System.Runtime.InteropServices.GCHandleType.Pinned); channel = Bass.BASS_StreamCreateFile(gcHandle.AddrOfPinnedObject(), 0L, length, decodeFlag); #else // #if MONO channel = Bass.BASS_StreamCreateFile(file.Path, 0, 0, decodeFlag); #endif } if (channel == 0) { #if MONO if (gcHandle.IsAllocated) { gcHandle.Free(); } #endif ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); return(0); } RunningFileInfo info = new RunningFileInfo(); bool isStreaming = BassStreamer.Instance.IsStreaming; bool useMultiSpeakerChannels = false; int speakers = 2; int origChannel = channel; if (!isStreaming && file.Effects != null && file.Effects.SpeakerAssignment.Active && file.Effects.SpeakerAssignment.Assignment == Data.SpeakerAssignment.AllSpeakers && !file.Effects.Balance.Active && !file.Effects.Pitch.Active && !file.Effects.Tempo.Active) { speakers = Bass.BASS_GetInfo().speakers; if (speakers > 2) { useMultiSpeakerChannels = true; } } Un4seen.Bass.BASSFlag flags = BASSFlag.BASS_DEFAULT; if (isStreaming) { flags = BASSFlag.BASS_FX_FREESOURCE | BASSFlag.BASS_STREAM_DECODE; } else if (useMultiSpeakerChannels) { flags = BASSFlag.BASS_FX_FREESOURCE | BASSFlag.BASS_STREAM_DECODE; } else { flags = BASSFlag.BASS_STREAM_AUTOFREE | BASSFlag.BASS_FX_FREESOURCE | speakerFlag; } channel = Un4seen.Bass.AddOn.Fx.BassFx.BASS_FX_TempoCreate(channel, flags); if (channel == 0) { #if MONO if (gcHandle.IsAllocated) { gcHandle.Free(); } #endif ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); return(0); } bool result = true; if (useMultiSpeakerChannels) { int splitStream = Un4seen.Bass.AddOn.Mix.BassMix.BASS_Split_StreamCreate(channel, BASSFlag.BASS_STREAM_AUTOFREE | BASSFlag.BASS_SPEAKER_FRONT, null); if (splitStream == 0) { result = false; } else { int splitStream2 = Un4seen.Bass.AddOn.Mix.BassMix.BASS_Split_StreamCreate(channel, BASSFlag.BASS_STREAM_AUTOFREE | BASSFlag.BASS_SPEAKER_REAR, null); if (splitStream2 == 0) { result = false; } else { Bass.BASS_ChannelSetLink(splitStream, splitStream2); info.LinkedChannels = new List <int>(); info.LinkedChannels.Add(splitStream2); } if (result && speakers > 4) { int splitStream3 = Un4seen.Bass.AddOn.Mix.BassMix.BASS_Split_StreamCreate(channel, BASSFlag.BASS_STREAM_AUTOFREE | BASSFlag.BASS_SPEAKER_CENLFE, null); if (splitStream3 == 0) { result = false; } else { Bass.BASS_ChannelSetLink(splitStream, splitStream3); info.LinkedChannels.Add(splitStream3); } } if (result && speakers > 6) { int splitStream4 = Un4seen.Bass.AddOn.Mix.BassMix.BASS_Split_StreamCreate(channel, BASSFlag.BASS_STREAM_AUTOFREE | BASSFlag.BASS_SPEAKER_REAR2, null); if (splitStream4 == 0) { result = false; } else { Bass.BASS_ChannelSetLink(splitStream, splitStream4); info.LinkedChannels.Add(splitStream4); } } if (result) { channel = splitStream; } } } if (result) { lock (m_Mutex) { info.EndAction = new Action(() => { callback(file.Id, channel); }); info.Volume = file.Volume; } if (!loop) { int sync = 0; // If CueOut is active ... if (file.Effects.CueOut.Active) { // Convert the CueOut position (seconds) into a byte offset long cueOutPos = Bass.BASS_ChannelSeconds2Bytes(channel, file.Effects.CueOut.Position); // Set the "end" sync to that position sync = Bass.BASS_ChannelSetSync(channel, BASSSync.BASS_SYNC_POS, cueOutPos, m_CueOutSync, new IntPtr(file.Id)); } else { long totalLength = Bass.BASS_ChannelGetLength(channel); long endingTime = Bass.BASS_ChannelSeconds2Bytes(channel, 0.1); // Default: set the "end" sync to the end of the stream, minus one ms sync = Bass.BASS_ChannelSetSync(channel, BASSSync.BASS_SYNC_POS, totalLength - endingTime, m_StartNextSync, IntPtr.Zero); } if (sync == 0) { #if MONO if (gcHandle.IsAllocated) { gcHandle.Free(); } #endif ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); return(0); } else { lock (m_Mutex) { m_NotLoops[channel] = sync; } } } if (!SetStartVolume(file, fadeInTime, channel, info)) { return(0); } info.CrossFade = false; if (file.Effects != null && file.Effects.FadeOutTime != 0) { long totalLength = Bass.BASS_ChannelGetLength(channel); if (totalLength == -1) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetVolumeError); return(0); } long fadeOutLength = Bass.BASS_ChannelSeconds2Bytes(channel, 0.001 * file.Effects.FadeOutTime); if (fadeOutLength == -1) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetVolumeError); return(0); } if (fadeOutLength > totalLength) { fadeOutLength = totalLength; } // If CueOut is active ... if (file.Effects.CueOut.Active) { // Convert the CueOut position (seconds) into a byte offset long cueOutPos = Bass.BASS_ChannelSeconds2Bytes(channel, file.Effects.CueOut.Position); // Set the "end" sync to that position if (Bass.BASS_ChannelSetSync(channel, BASSSync.BASS_SYNC_POS, cueOutPos - fadeOutLength, m_FadeOutSync, new IntPtr(file.Effects.FadeOutTime)) == 0) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); return(0); } } else { if (Bass.BASS_ChannelSetSync(channel, BASSSync.BASS_SYNC_POS, totalLength - fadeOutLength, m_FadeOutSync, new IntPtr(file.Effects.FadeOutTime)) == 0) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); return(0); } } if (loop) { // If CueOut is active ... if (file.Effects.CueOut.Active) { // Convert the CueOut position (seconds) into a byte offset long cueOutPos = Bass.BASS_ChannelSeconds2Bytes(channel, file.Effects.CueOut.Position); // Set the "end" sync to that position if (Bass.BASS_ChannelSetSync(channel, BASSSync.BASS_SYNC_POS, cueOutPos, m_LoopSync, new IntPtr(file.Id)) == 0) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); return(0); } } else { if (Bass.BASS_ChannelSetSync(channel, BASSSync.BASS_SYNC_POS, totalLength, m_LoopSync, new IntPtr(file.Id)) == 0) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); return(0); } } } else { info.CrossFade = file.Effects.CrossFading; } } if (file.Effects != null && file.Effects.Pitch.Active) { float pitchValue = DetermineIntEffectValue(file.Effects.Pitch); if (!Bass.BASS_ChannelSetAttribute(channel, BASSAttribute.BASS_ATTRIB_TEMPO_PITCH, pitchValue)) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } } if (file.Effects != null && file.Effects.Tempo.Active) { float tempoValue = DetermineIntEffectValue(file.Effects.Tempo); if (!Bass.BASS_ChannelSetAttribute(channel, BASSAttribute.BASS_ATTRIB_TEMPO, tempoValue)) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } } if (file.Effects != null && file.Effects.Balance.Active && !useMultiSpeakerChannels) { SetBalanceEffect(channel, file.Id, file.Effects.Balance); } if (file.Effects != null && file.Effects.VolumeDB.Active) { float volumeDB = DetermineIntEffectValue(file.Effects.VolumeDB); float linear = (float)Math.Pow(10d, volumeDB / 20); int volFx = Bass.BASS_ChannelSetFX(channel, BASSFXType.BASS_FX_BFX_VOLUME, 1); if (volFx == 0) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } Un4seen.Bass.AddOn.Fx.BASS_BFX_VOLUME fxVol = new Un4seen.Bass.AddOn.Fx.BASS_BFX_VOLUME(linear, Un4seen.Bass.AddOn.Fx.BASSFXChan.BASS_BFX_CHANALL); if (!Bass.BASS_FXSetParameters(volFx, fxVol)) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } if (info.LinkedChannels != null) { foreach (int splitStream2 in info.LinkedChannels) { int volFx2 = splitStream2 != 0 ? Bass.BASS_ChannelSetFX(splitStream2, BASSFXType.BASS_FX_BFX_VOLUME, 1) : 0; if (splitStream2 != 0 && volFx2 == 0) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } if (volFx2 != 0 && !Bass.BASS_FXSetParameters(volFx2, fxVol)) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } } } } #pragma warning disable CS0618 // Type or member is obsolete if (file.Effects != null && file.Effects.Reverb.Active) { float linearLevel = (float)Math.Pow(10d, file.Effects.Reverb.Level / 20); int reverbFx = Bass.BASS_ChannelSetFX(channel, BASSFXType.BASS_FX_BFX_REVERB, 1); if (reverbFx == 0) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } Un4seen.Bass.AddOn.Fx.BASS_BFX_REVERB fxReverb = new Un4seen.Bass.AddOn.Fx.BASS_BFX_REVERB(linearLevel, file.Effects.Reverb.Delay); if (!Bass.BASS_FXSetParameters(reverbFx, fxReverb)) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } if (info.LinkedChannels != null) { foreach (int splitStream2 in info.LinkedChannels) { int reverbFx2 = splitStream2 != 0 ? Bass.BASS_ChannelSetFX(splitStream2, BASSFXType.BASS_FX_BFX_REVERB, 1) : 0; if (splitStream2 != 0 && reverbFx2 == 0) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } if (reverbFx2 != 0 && !Bass.BASS_FXSetParameters(reverbFx2, fxReverb)) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.SetEffectError); return(0); } } } } #pragma warning restore CS0618 // Type or member is obsolete if (loop) { Bass.BASS_ChannelFlags(channel, BASSFlag.BASS_SAMPLE_LOOP, BASSFlag.BASS_SAMPLE_LOOP); } lock (m_Mutex) { m_Loops[file.Id] = file; if (file.Effects != null && file.Effects.CueOut.Active) { m_CueOutRepeats[channel] = loop; } } if (file.Effects.CueIn.Active) { Bass.BASS_ChannelSetPosition(channel, file.Effects.CueIn.Position); } if (isStreaming) { result = BassStreamer.Instance.AddChannel(channel); } else { result = Bass.BASS_ChannelPlay(channel, false); } if (!result) { ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); Bass.BASS_StreamFree(channel); #if MONO if (gcHandle.IsAllocated) { gcHandle.Free(); } #endif return(0); } lock (m_Mutex) { m_RunningFiles[channel] = info; #if MONO if (gcHandle.IsAllocated) { m_GCHandles[channel] = gcHandle; } #endif } return(channel); } else { ErrorHandling.BassErrorOccurred(file.Id, StringResources.FilePlayingError); return(0); } }
public virtual void CopyImageData(byte[] data, int bufferSize, int bytesPerPixel) { System.Runtime.InteropServices.GCHandle pinHandle_data = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { { SharingClientPINVOKE.TagImage_CopyImageData(swigCPtr, (System.IntPtr)pinHandle_data.AddrOfPinnedObject(), bufferSize, bytesPerPixel); } } finally { pinHandle_data.Free(); } }
public virtual bool UploadAnchor(Room room, XString anchorName, byte[] data, int dataSize) { System.Runtime.InteropServices.GCHandle pinHandle_data = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { { bool ret = SharingClientPINVOKE.RoomManager_UploadAnchor(swigCPtr, Room.getCPtr(room), XString.getCPtr(anchorName), (System.IntPtr)pinHandle_data.AddrOfPinnedObject(), dataSize); return(ret); } } finally { pinHandle_data.Free(); } }
public virtual bool ProcessImage(byte[] image, int width, int height, int bytesPerPixel) { System.Runtime.InteropServices.GCHandle pinHandle_image = System.Runtime.InteropServices.GCHandle.Alloc(image, System.Runtime.InteropServices.GCHandleType.Pinned); try { { bool ret = SharingClientPINVOKE.VisualPairConnector_ProcessImage(swigCPtr, (System.IntPtr)pinHandle_image.AddrOfPinnedObject(), width, height, bytesPerPixel); return(ret); } } finally { pinHandle_image.Free(); } }
public static void CreateAndSendMeshRequest(Mesh mesh, List <string> materialTokens, string token) { MeshData meshData = new MeshData(); meshData.entityToken = token; meshData.entityParentToken = ""; meshData.displayName = mesh.name; // Add positions, first convert from Unity to STP Vector3[] vertices = new Vector3[mesh.vertices.Length]; System.Array.Copy(mesh.vertices, vertices, mesh.vertices.Length); int vertCount = vertices.Length; for (int i = vertCount - 1; i >= 0; i--) { float tempY = vertices[i].y; vertices[i].y = -vertices[i].z; vertices[i].z = tempY; vertices[i].Scale(MarshalData.scaleFromUnitytoSTP); } System.Runtime.InteropServices.GCHandle pinnedVerticesArray = System.Runtime.InteropServices.GCHandle.Alloc(vertices, System.Runtime.InteropServices.GCHandleType.Pinned); meshData.positions = pinnedVerticesArray.AddrOfPinnedObject(); meshData.positionsNum = (System.UIntPtr)(vertices.Length * verticesDataStride); // Add normals Vector3[] normals = new Vector3[mesh.normals.Length]; System.Array.Copy(mesh.normals, normals, mesh.normals.Length); int normalCount = mesh.normals.Length; for (int i = normalCount - 1; i >= 0; i--) { float tempY = normals[i].y; normals[i].y = -normals[i].z; normals[i].z = tempY; } System.Runtime.InteropServices.GCHandle pinnedNormalsArray = System.Runtime.InteropServices.GCHandle.Alloc(normals, System.Runtime.InteropServices.GCHandleType.Pinned); meshData.normals = pinnedNormalsArray.AddrOfPinnedObject(); meshData.normalsNum = (System.UIntPtr)(normals.Length * normalsDataStride); // Add indices meshData.facesetsNum = (System.IntPtr)mesh.subMeshCount; System.Runtime.InteropServices.GCHandle[] pinnedIndicesArrays = new System.Runtime.InteropServices.GCHandle[(int)meshData.facesetsNum]; // Add facesets FacesetData[] faceSets = new FacesetData[(int)meshData.facesetsNum]; int structSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(FacesetData)); meshData.facesets = System.Runtime.InteropServices.Marshal.AllocHGlobal((int)meshData.facesetsNum * structSize); System.IntPtr facesetsPtr = meshData.facesets; // Change the winding order of indices int[][] indices = new int[(int)meshData.facesetsNum][]; var materialNum = materialTokens.Count; for (var i = 0; i < (int)meshData.facesetsNum; ++i) { int[] indicesList = mesh.GetTriangles(i); indices[i] = new int[indicesList.Length]; for (var indicePos = 0; indicePos < indicesList.Length; indicePos += indicesStride) { indices[i][indicePos + 0] = indicesList[indicePos + 0]; indices[i][indicePos + 1] = indicesList[indicePos + 2]; indices[i][indicePos + 2] = indicesList[indicePos + 1]; } pinnedIndicesArrays[i] = System.Runtime.InteropServices.GCHandle.Alloc( indices[i], System.Runtime.InteropServices.GCHandleType.Pinned ); faceSets[i].indices = pinnedIndicesArrays[i].AddrOfPinnedObject(); // Marshaling needs to use UIntPtr for size_t int indicesNum = indicesList.Length; //faceSets[i].indicesNum = (System.UIntPtr)indicesNum; faceSets[i].indicesNum = (ulong)indicesNum; // Marshal material tokens if (i < materialNum) { faceSets[i].materialName = materialTokens[i]; } else { faceSets[i].materialName = ""; } System.Runtime.InteropServices.Marshal.StructureToPtr(faceSets[i], facesetsPtr, false); facesetsPtr = (System.IntPtr)((long)facesetsPtr + structSize); } // Add UVs List <Vector2>[] meshUVs = new List <Vector2> [maxUV]; int uvCount = 0; for (int i = 0; i < maxUV; i++) { meshUVs[i] = new List <Vector2>(); mesh.GetUVs(i, meshUVs[i]); if (meshUVs[i].Count == 0) { break; } uvCount++; } UVData[] uvSets = new UVData[uvCount]; float[][] uvDataArr = new float[uvCount][]; structSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(UVData)); meshData.uvSetNum = (System.IntPtr)uvCount; meshData.uvSets = System.Runtime.InteropServices.Marshal.AllocHGlobal(uvCount * structSize); System.IntPtr uvSetsPtr = meshData.uvSets; System.Runtime.InteropServices.GCHandle[] pinnedUVArrays = new System.Runtime.InteropServices.GCHandle[uvCount]; for (int i = 0; i < uvCount; i++) { uvDataArr[i] = new float[meshUVs[i].Count * uvDataStride]; for (int uvInd = 0; uvInd < meshUVs[i].Count; uvInd++) { int uvDataInd = uvInd * uvDataStride; uvDataArr[i][uvDataInd] = meshUVs[i][uvInd].x; uvDataArr[i][uvDataInd + 1] = 1.0f - meshUVs[i][uvInd].y; // Convert UV from Unity to STP } // We are not using UV indices due to Unity not supporting them uvSets[i].indicesNum = 0; pinnedUVArrays[i] = System.Runtime.InteropServices.GCHandle.Alloc( uvDataArr[i], System.Runtime.InteropServices.GCHandleType.Pinned ); uvSets[i].uvs = pinnedUVArrays[i].AddrOfPinnedObject(); uvSets[i].uvsNum = (ulong)uvDataArr[i].Length; System.Runtime.InteropServices.Marshal.StructureToPtr(uvSets[i], uvSetsPtr, false); uvSetsPtr = (System.IntPtr)((long)uvSetsPtr + structSize); } System.IntPtr meshDataPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(meshData)); System.Runtime.InteropServices.Marshal.StructureToPtr(meshData, meshDataPtr, false); Debug.LogFormat("Mesh Push - Token:{0}, Parent:{1}, {2} positions, {3} facesets", meshData.entityToken, meshData.entityParentToken, (int)meshData.positionsNum, (int)meshData.facesetsNum); ImportMenu.stpUnitySendMeshData(meshDataPtr); // Free memory pinnedVerticesArray.Free(); pinnedNormalsArray.Free(); foreach (var pin in pinnedIndicesArrays) { pin.Free(); } System.Runtime.InteropServices.Marshal.FreeHGlobal(meshData.facesets); System.Runtime.InteropServices.Marshal.FreeHGlobal(meshDataPtr); }
public Dictionary <string, Dictionary <string, string> > getVideoInfo(Stream fileStream) { Dictionary <string, Dictionary <string, string> > exif = new Dictionary <string, Dictionary <string, string> >(); try { if (fileStream.CanSeek) { byte[] buffer = new byte[64 * 1024]; int bufferSize = 0; using (MediaInfo mediaInfo = new MediaInfo()) { mediaInfo.Open_Buffer_Init(fileStream.Length, 0); do { //Reading data somewhere, do what you want for this. bufferSize = fileStream.Read(buffer, 0, 64 * 1024); //Sending the buffer to MediaInfo System.Runtime.InteropServices.GCHandle GC = System.Runtime.InteropServices.GCHandle.Alloc(buffer, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr From_Buffer_IntPtr = GC.AddrOfPinnedObject(); Status Result = (Status)mediaInfo.Open_Buffer_Continue(From_Buffer_IntPtr, (IntPtr)bufferSize); GC.Free(); if ((Result & Status.Finalized) == Status.Finalized) { break; } //Testing if MediaInfo request to go elsewhere if (mediaInfo.Open_Buffer_Continue_GoTo_Get() != -1) { Int64 Position = fileStream.Seek(mediaInfo.Open_Buffer_Continue_GoTo_Get(), SeekOrigin.Begin); //Position the file mediaInfo.Open_Buffer_Init(fileStream.Length, Position); //Informing MediaInfo we have seek } }while (bufferSize > 0); string t = mediaInfo.Option("Info_Parameters"); Dictionary <string, string> tmp = new Dictionary <string, string>(); if (mediaInfo.Count_Get(StreamKind.Video) != 0) { tmp = new Dictionary <string, string>(); tmp.Add("Title", mediaInfo.Get(StreamKind.Video, 0, "Title")); tmp.Add("Width", mediaInfo.Get(StreamKind.Video, 0, "Width")); tmp.Add("Height", mediaInfo.Get(StreamKind.Video, 0, "Height")); tmp.Add("Duration", mediaInfo.Get(StreamKind.Video, 0, "Duration/String3")); exif.Add("Video", tmp); } if (mediaInfo.Count_Get(StreamKind.Audio) != 0) { tmp = new Dictionary <string, string>(); tmp.Add("Title", mediaInfo.Get(StreamKind.Audio, 0, "Title")); tmp.Add("Duration", mediaInfo.Get(StreamKind.Audio, 0, "Duration/String3")); exif.Add("Audio", tmp); } return(exif); } } else { return(exif); } } catch { return(exif); } }
public virtual bool GetData(byte[] data, int dataSize) { System.Runtime.InteropServices.GCHandle pinHandle_data = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { { bool ret = SharingClientPINVOKE.AnchorDownloadRequest_GetData(swigCPtr, (System.IntPtr)pinHandle_data.AddrOfPinnedObject(), dataSize); return(ret); } } finally { pinHandle_data.Free(); } }
private void FormDebugging_Load(object sender, EventArgs e) { frmWhiteBoard = new FormWhiteBoard(); frmWhiteBoard.Show(); byte x; x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT);// x is 1 GL.Disable(GL.GL_DEBUG_OUTPUT); x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT);// x is 0 GL.Enable(GL.GL_DEBUG_OUTPUT); x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT);// x is 1 x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);// x is 0 GL.Disable(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);// x is 0 GL.Enable(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); x = GL.IsEnabled(GL.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);// x is 1 // 必须是struct UserParamStruct data = new UserParamStruct() { integer = 123, handle = this.glCanvas1.Handle }; this.userParamInstance = System.Runtime.InteropServices.GCHandle.Alloc( data, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr ptr = userParamInstance.AddrOfPinnedObject(); GL.DebugMessageCallback(this.callbackProc, ptr); GL.DebugMessageControl( Enumerations.DebugMessageControlSource.DONT_CARE, Enumerations.DebugMessageControlType.DONT_CARE, Enumerations.DebugMessageControlSeverity.DONT_CARE, 0, null, true); StringBuilder builder = new StringBuilder(); builder.Append("hello, this is app!"); GL.DebugMessageInsert( Enumerations.DebugSource.DEBUG_SOURCE_APPLICATION_ARB, Enumerations.DebugType.DEBUG_TYPE_OTHER_ARB, 0x4752415A, //Enumerations.DebugSeverity.DEBUG_SEVERITY_NOTIFICATION_ARB,// not valid Enumerations.DebugSeverity.DEBUG_SEVERITY_HIGH_ARB, //Enumerations.DebugSeverity.DEBUG_SEVERITY_MEDIUM_ARB, //Enumerations.DebugSeverity.DEBUG_SEVERITY_LOW_ARB, -1, builder); }