System.Runtime.InteropServices.Marshal.Copy(System.IntPtr, byte[], int, int)

Here are the examples of the csharp api System.Runtime.InteropServices.Marshal.Copy(System.IntPtr, byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

936 Examples 7

19 View Source File : graybitmap.cs
License : MIT License
Project Creator : altimesh

public void Save(string filename)
        {
            using (BinaryWriter bw = new BinaryWriter(new FileStream(filename, FileMode.OpenOrCreate)))
            {
                // write headers
                FileHeader header = FileHeader.GrayBitmap(width, height);
                BitmapInfoHeader bih = BitmapInfoHeader.GrayBitmap(width, height);

                byte[] head = new byte[54];

                GCHandle gch = GCHandle.Alloc(header, GCHandleType.Pinned);
                Marshal.Copy(gch.AddrOfPinnedObject(), head, 0, 14);
                gch.Free();

                gch = GCHandle.Alloc(bih, GCHandleType.Pinned);
                Marshal.Copy(gch.AddrOfPinnedObject(), head, 14, 40);
                gch.Free();

                bw.Write(head, 0, 54);

                // write color table
                uint[] colors = new uint[256];
                uint color = 0;
                uint next = 0x010101;
                for (int k = 0; k < 256; ++k)
                {
                    bw.Write(color);
                    color += next;
                }

                // write data - note that bmp starts with bottom-left corner
                for (int y = 0; y < height; ++y)
                    bw.Write(data, (int)width * ((int)height - 1 - y), (int)width);
            }
        }

19 View Source File : YukkuriModel.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void TextToWave(
            string textToSpeak,
            string waveFileName,
            int speed)
        {
            if (string.IsNullOrWhiteSpace(textToSpeak))
            {
                return;
            }

            if (this.SynthesizeDelegate == null ||
                this.FreeWaveDelegate == null)
            {
                return;
            }

            var wavePtr = IntPtr.Zero;

            try
            {
                // テキストを音声データに変換する
                uint size = 0;
                wavePtr = this.SynthesizeDelegate.Invoke(
                    textToSpeak,
                    (ushort)speed,
                    ref size);

                if (wavePtr == IntPtr.Zero ||
                    size <= 0)
                {
                    return;
                }

                FileHelper.CreateDirectory(waveFileName);

                // 生成したwaveデータを読み出す
                var buff = new byte[size];
                Marshal.Copy(wavePtr, buff, 0, (int)size);
                using (var fs = new FileStream(waveFileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buff, 0, buff.Length);
                }
            }
            finally
            {
                if (wavePtr != IntPtr.Zero)
                {
                    this.FreeWaveDelegate.Invoke(wavePtr);
                }
            }
        }

19 View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static byte[] ExtractImageData(Bitmap bitmap)
		{
			byte[] bsData = null;
			{
				int width = bitmap.Width;
				int height = bitmap.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);

				var data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
				try
				{
					IntPtr pData = new IntPtr(data.Scan0.ToInt64() + (data.Stride > 0 ? 0 : data.Stride * (height - 1)));
					int length = Math.Abs(data.Stride) * data.Height;
					bsData = new byte[length];
					Marshal.Copy(pData, bsData, 0, length);
				}
				catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
				finally
				{
					bitmap.UnlockBits(data);
				}
			}
			return bsData;
		}

19 View Source File : FirmwareTable.cs
License : MIT License
Project Creator : AlexGyver

public static string[] EnumerateTables(Provider provider) {
      int size;
      try {
        size = NativeMethods.EnumSystemFirmwareTables(
          provider, IntPtr.Zero, 0);
      } catch (DllNotFoundException) { return null; } 
        catch (EntryPointNotFoundException) { return null; }

      IntPtr nativeBuffer = Marshal.AllocHGlobal(size);
      NativeMethods.EnumSystemFirmwareTables(
        provider, nativeBuffer, size);
      byte[] buffer = new byte[size];
      Marshal.Copy(nativeBuffer, buffer, 0, size);
      Marshal.FreeHGlobal(nativeBuffer);

      string[] result = new string[size / 4];
      for (int i = 0; i < result.Length; i++) 
        result[i] = Encoding.ASCII.GetString(buffer, 4 * i, 4);

      return result;
    }

19 View Source File : StructHelper.cs
License : MIT License
Project Creator : albyho

public static byte[] StructToBytes<T>(T structObj) where T : struct
        {
            //得到结构体的大小
            Int32 size = Marshal.SizeOf(structObj);
            //创建byte数组
            var bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(structObj, structPtr, false);
            //从内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }

19 View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static byte[] XorGrayscaleImage(Image bgImage, Image srcImage, float ratio)
		{
			Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
			Debug.replacedert(0 < ratio && ratio < 1);

			byte[] bsXor = null;
			try
			{
				int width = bgImage.Width;
				int height = bgImage.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);
				long diffMax = (int)(width * height * ratio);
				long diffCount = 0;

				using (Bitmap srcBmp = new Bitmap(srcImage))
				using (Bitmap bkgBmp = new Bitmap(bgImage))
				using (Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed))
				{
					BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
					BitmapData bkgData = bkgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
					BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
					Debug.replacedert(srcData.Stride == bkgData.Stride && srcData.Stride == newData.Stride);
					Debug.replacedert(srcData.Stride % 4 == 0);
					int stride = srcData.Stride;
					unsafe
					{
						byte* pSrc = (byte*)srcData.Scan0.ToPointer();
						byte* pBkg = (byte*)bkgData.Scan0.ToPointer();
						byte* pNew = (byte*)newData.Scan0.ToPointer();
						uint* ps, pg, pn;
						for (int y = 0; y < height; ++y)
						{
							ps = (uint*)(pSrc + (stride * y));
							pg = (uint*)(pBkg + (stride * y));
							pn = (uint*)(pNew + (stride * y));
							for (int x = 0; x < width; x += 4)
							{
								*pn = *pg ^ *ps;
								++ps;
								++pg;
								++pn;

								diffCount += ((*pg == *ps) ? 0 : 4);
							}
							if (diffCount >= diffMax)
								break;
						}
					}
					if (diffCount < diffMax)
					{
						bsXor = new byte[newData.Stride * newData.Height];
						Marshal.Copy(newData.Scan0, bsXor, 0, bsXor.Length);
					}
					srcBmp.UnlockBits(srcData);
					bkgBmp.UnlockBits(bkgData);
					newBmp.UnlockBits(newData);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return bsXor;
		}

19 View Source File : BuilderPlug.cs
License : GNU General Public License v3.0
Project Creator : anotak

private static Bitmap MakeTintedImage(Bitmap source, PixelColor tint) 
		{
			BitmapData sourcedata = source.LockBits(new Rectangle(0, 0, source.Width, source.Height),
									ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

			byte[] pixelBuffer = new byte[sourcedata.Stride * sourcedata.Height];
			Marshal.Copy(sourcedata.Scan0, pixelBuffer, 0, pixelBuffer.Length);
			source.UnlockBits(sourcedata);

			//Translate tint color to 0.0-1.0 range
			float redtint = tint.r / 256.0f;
			float greentint = tint.g / 256.0f; 
			float bluetint = tint.b / 256.0f;

			for(int k = 0; k + 4 < pixelBuffer.Length; k += 4) 
			{
				float blue = 60 + pixelBuffer[k] * bluetint;
				float green = 60 + pixelBuffer[k + 1] * greentint;
				float red = 60 + pixelBuffer[k + 2] * redtint;

				pixelBuffer[k] = (byte)Math.Min(255, blue);
				pixelBuffer[k + 1] = (byte)Math.Min(255, green);
				pixelBuffer[k + 2] = (byte)Math.Min(255, red);
			}

			Bitmap result = new Bitmap(source.Width, source.Height);
			BitmapData resultdata = result.LockBits(new Rectangle(0, 0, result.Width, result.Height),
									ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

			Marshal.Copy(pixelBuffer, 0, resultdata.Scan0, pixelBuffer.Length);
			result.UnlockBits(resultdata);

			return result;
		}

19 View Source File : UnmanagedBuffer.cs
License : Apache License 2.0
Project Creator : aequabit

public byte[] Read(int count)
        {
            try
            {
                if ((count > this.Size) || (count <= 0))
                {
                    throw new ArgumentException("There is either not enough memory allocated to read 'count' bytes, or 'count' is negative (" + count.ToString() + ")", "count");
                }
                byte[] destination = new byte[count];
                Marshal.Copy(this.Pointer, destination, 0, count);
                return destination;
            }
            catch (Exception exception)
            {
                this.SetLastError(exception);
                return null;
            }
        }

19 View Source File : CbgEncoder.cs
License : MIT License
Project Creator : arcusmaximus

private static byte[] GetPixels(Image image)
        {
            using (Bitmap bitmap = new Bitmap(image))
            {
                Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
                BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                byte[] pixels = new byte[bitmapData.Stride * bitmap.Height];
                Marshal.Copy(bitmapData.Scan0, pixels, 0, pixels.Length);
                bitmap.UnlockBits(bitmapData);
                return pixels;
            }
        }

19 View Source File : CustomAudioSinkSample.cs
License : MIT License
Project Creator : AgoraIO

private void PullAudioFrameThread()
        {
            var avsync_type = 0;
            var bytesPerSample = 2;
            var type = AUDIO_FRAME_TYPE.FRAME_TYPE_PCM16;
            var channels = CHANNEL;
            var samples = SAMPLE_RATE / PULL_FREQ_PER_SEC * CHANNEL;
            var samplesPerSec = SAMPLE_RATE;
            var buffer = Marshal.AllocHGlobal(samples * bytesPerSample);
            var freq = 1000 / PULL_FREQ_PER_SEC;

            var tic = new TimeSpan(DateTime.Now.Ticks);

            while (_pullAudioFrameThreadSignal)
            {
                var toc = new TimeSpan(DateTime.Now.Ticks);
                if (toc.Subtract(tic).Duration().Milliseconds >= freq)
                {
                    tic = new TimeSpan(DateTime.Now.Ticks);
                    _audioRawDataManager.PullAudioFrame(buffer, (int) type, samples, bytesPerSample, channels,
                        samplesPerSec, 0, avsync_type);

                    var byteArray = new byte[samples * bytesPerSample];
                    Marshal.Copy(buffer, byteArray, 0, samples * bytesPerSample);

                    var floatArray = ConvertByteToFloat16(byteArray);
                    lock (audioBuffer)
                    {
                        audioBuffer.Put(floatArray);
                    }

                    writeCount += floatArray.Length;
                    count += 1;
                }

                if (count == 100)
                {
                    _startSignal = true;
                }
            }

            Marshal.FreeHGlobal(buffer);
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : ALEXGREENALEX

public Bitmap Gray16To8bppIndexed(Bitmap BmpIn)
        {
            if (BmpIn.PixelFormat != PixelFormat.Format16bppGrayScale)
                throw new BadImageFormatException();

            byte[] ImageData = new byte[BmpIn.Width * BmpIn.Height * 2];
            Rectangle Re = new Rectangle(0, 0, BmpIn.Width, BmpIn.Height);

            BitmapData BmpData = BmpIn.LockBits(Re, ImageLockMode.ReadOnly, BmpIn.PixelFormat);
            Marshal.Copy(BmpData.Scan0, ImageData, 0, ImageData.Length);
            BmpIn.UnlockBits(BmpData);

            byte[] ImageData2 = new byte[BmpIn.Width * BmpIn.Height];
            for (long i = 0; i < ImageData2.LongLength; i++)
                ImageData2[i] = ImageData[i * 2 + 1];
            ImageData = null;

            Bitmap BmpOut = new Bitmap(BmpIn.Width, BmpIn.Height, PixelFormat.Format8bppIndexed);
            BmpData = BmpOut.LockBits(Re, ImageLockMode.WriteOnly, BmpOut.PixelFormat);
            Marshal.Copy(ImageData2, 0, BmpData.Scan0, ImageData2.Length);
            BmpOut.UnlockBits(BmpData);
            ImageData2 = null;
            BmpData = null;

            ColorPalette GrayPalette = BmpOut.Palette;
            Color[] GrayColors = GrayPalette.Entries;
            for (int i = 0; i < GrayColors.Length; i++)
                GrayColors[i] = Color.FromArgb(i, i, i);
            BmpOut.Palette = GrayPalette;

            return BmpOut;
        }

19 View Source File : Reflection.cs
License : MIT License
Project Creator : AlenToma

public unsafe static byte[] UnicodeGetBytes(string str)
        {
            int len = str.Length * 2;
            byte[] b = new byte[len];
            fixed (void* ptr = str)
            {
                System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), b, 0, len);
            }
            return b;
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ahuchjm

List<NumBody> FindText(string subPic, string parPic, System.Drawing.Rectangle searchRect, byte errorRange, double matchRate = 0.9, bool isFindAll = false)
        {

            List<NumBody> ListPoint = new List<NumBody>();
            var subBitmap = new Bitmap(subPic);
            var parBitmap = new Bitmap(parPic);
            int subWidth = subBitmap.Width;
            int subHeight = subBitmap.Height;
            int parWidth = parBitmap.Width;
            int parHeight = parBitmap.Height;
            var bgColor = subBitmap.GetPixel(0, 0);//背景红色
            if (searchRect.IsEmpty)
            {
                searchRect = new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height);
            }
            var searchLeftTop = searchRect.Location;
            var searchSize = searchRect.Size;
            var subData = subBitmap.LockBits(new System.Drawing.Rectangle(0, 0, subBitmap.Width, subBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var parData = parBitmap.LockBits(new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var byteArrarySub = new byte[subData.Stride * subData.Height];
            var byteArraryPar = new byte[parData.Stride * parData.Height];
            Marshal.Copy(subData.Scan0, byteArrarySub, 0, subData.Stride * subData.Height);
            Marshal.Copy(parData.Scan0, byteArraryPar, 0, parData.Stride * parData.Height);
            var iMax = searchLeftTop.Y + searchSize.Height - subData.Height;//行
            var jMax = searchLeftTop.X + searchSize.Width - subData.Width;//列
            System.Drawing.Color startPixelColor = System.Drawing.Color.FromArgb(0, 0, 0);
            int smallOffsetX = 0, smallOffsetY = 0;
            int smallStartX = 0, smallStartY = 0;
            int pointX = -1; int pointY = -1;


            for (int m = 0; m < subHeight; m++)
            {
                for (int n = 0; n < subWidth; n++)
                {
                    smallOffsetX = n;
                    smallOffsetY = m;
                    int subIndex = m * subWidth * 4 + n * 4;
                    var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);
                    if (!ColorAEqualColorB(color, bgColor, errorRange))
                    {
                        startPixelColor = color;
                        goto END;
                    }
                }
            }

        END:
            for (int i = searchLeftTop.Y; i < iMax; i++)
            {
                for (int j = searchLeftTop.X; j < jMax; j++)
                {
                    //大图x,y坐标处的颜色值
                    int x = j, y = i;
                    int parIndex = i * parWidth * 4 + j * 4;
                    var colorBig = System.Drawing.Color.FromArgb(byteArraryPar[parIndex + 3], byteArraryPar[parIndex + 2], byteArraryPar[parIndex + 1], byteArraryPar[parIndex]);
                    ;

                    List<System.Drawing.Point> myListPoint = new List<System.Drawing.Point>();
                    if (ColorAEqualColorB(colorBig, startPixelColor, errorRange))
                    {
                        smallStartX = x - smallOffsetX;//待找的图X坐标
                        smallStartY = y - smallOffsetY;//待找的图Y坐标
                        int sum = 0;//所有需要比对的有效点
                        int matchNum = 0;//成功匹配的点
                        for (int m = 0; m < subHeight; m++)
                        {
                            for (int n = 0; n < subWidth; n++)
                            {
                                int x1 = n, y1 = m;
                                int subIndex = m * subWidth * 4 + n * 4;
                                var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);
                                if (color != bgColor)
                                {
                                    sum++;
                                    int x2 = smallStartX + x1, y2 = smallStartY + y1;
                                    int parReleativeIndex = y2 * parWidth * 4 + x2 * 4;//比对大图对应的像素点的颜色
                                    var colorPixel = System.Drawing.Color.FromArgb(byteArraryPar[parReleativeIndex + 3], byteArraryPar[parReleativeIndex + 2], byteArraryPar[parReleativeIndex + 1], byteArraryPar[parReleativeIndex]);
                                    if (ColorAEqualColorB(colorPixel, color, errorRange))
                                    {
                                        matchNum++;
                                    }
                                    myListPoint.Add(new System.Drawing.Point(x2, y2));
                                }
                            }
                        }

                        double rate = (double)matchNum / sum;
                        if (rate>= matchRate)
                        {
                            Console.WriteLine((double)matchNum / sum);
                            pointX = smallStartX + (int)(subWidth / 2.0);
                            pointY = smallStartY + (int)(subHeight / 2.0);
                            var point = new System.Drawing.Point(pointX, pointY);
                            if (!ListTextBodyContainsPoint(ListPoint, point, 1))
                            {
                                ListPoint.Add(new NumBody() { point = point, matchNum = matchNum,matchSum=sum, matchRate = rate, bodyCollectionPoint = myListPoint });
                            }
                            SearchNumbersByMatchNum(ref ListPoint);
                            if (!isFindAll)
                            {
                                goto FIND_END;
                            }
                        }
                    }
                    //小图x1,y1坐标处的颜色值
                }
            }
        FIND_END:
            subBitmap.UnlockBits(subData);
            parBitmap.UnlockBits(parData);
            subBitmap.Dispose();
            parBitmap.Dispose();
            GC.Collect();
            return ListPoint;
        }

19 View Source File : ObjectToByte.cs
License : MIT License
Project Creator : allartprotocol

public static byte[] getBytes(CompiledInstruction str)
        {
            int size = Marshal.SizeOf(str);
            byte[] arr = new byte[size];

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(str, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }

19 View Source File : NativeMethods.cs
License : GNU General Public License v2.0
Project Creator : ADeltaX

public static string _GetMessage(Message m)
		{
			string msg = null;
			if (m.Msg == NativeMethods.WM_COPYDATA)
			{
				if (InSendMessage()) ReplyMessage(IntPtr.Zero);
				COPYDATASTRUCT data = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
				byte[] b = new byte[data.cbData];
				Marshal.Copy(data.lpData, b, 0, data.cbData);
				msg = Encoding.UTF8.GetString(b);
			}
			return msg;
		}

19 View Source File : EdgeDetector.cs
License : Apache License 2.0
Project Creator : andijakl

private static void Sobel(byte[] outputImage, IntPtr inputImage, int width, int height)
        {
            // Adjust buffer size if necessary.
            int bufferSize = width * height;
            if (bufferSize != s_ImageBufferSize || s_ImageBuffer.Length == 0)
            {
                s_ImageBufferSize = bufferSize;
                s_ImageBuffer = new byte[bufferSize];
            }

            // Move raw data into managed buffer.
            System.Runtime.InteropServices.Marshal.Copy(inputImage, s_ImageBuffer, 0, bufferSize);

            // Detect edges.
            int threshold = 128 * 128;
            
            for (int j = 1; j < height - 1; j++)
            {
                for (int i = 1; i < width - 1; i++)
                {
                    // Offset of the pixel at [i, j] of the input image.
                    int offset = (j * width) + i;

                    // Neighbour pixels around the pixel at [i, j].
                    int a00 = s_ImageBuffer[offset - width - 1];
                    int a01 = s_ImageBuffer[offset - width];
                    int a02 = s_ImageBuffer[offset - width + 1];
                    int a10 = s_ImageBuffer[offset - 1];
                    int a12 = s_ImageBuffer[offset + 1];
                    int a20 = s_ImageBuffer[offset + width - 1];
                    int a21 = s_ImageBuffer[offset + width];
                    int a22 = s_ImageBuffer[offset + width + 1];

                    // Sobel X filter:
                    //   -1, 0, 1, 
                    //   -2, 0, 2, 
                    //   -1, 0, 1 
                    int xSum = -a00 - (2 * a10) - a20 + a02 + (2 * a12) + a22;

                    // Sobel Y filter:
                    //    1, 2, 1, 
                    //    0, 0, 0, 
                    //   -1, -2, -1 
                    int ySum = a00 + (2 * a01) + a02 - a20 - (2 * a21) - a22;
                    
                    if ((xSum * xSum) + (ySum * ySum) > threshold)
                    {
                        outputImage[(j * width) + i] = 0xFF;
                    }
                    else
                    {
                        outputImage[(j * width) + i] = 0x1F;
                    }
                }
            }
        }

19 View Source File : CustomScanner.cs
License : Apache License 2.0
Project Creator : airbus-cert

internal List<ScanResult> ScanMemory(
            IntPtr buffer,
            int length,
            ExternalVariables externalVariables,
            YR_SCAN_FLAGS flags)
        {
            byte[] res = new byte[length - 1];
            Marshal.Copy(buffer, res, 0, length);
            return ScanMemory(ref res, length, externalVariables, flags);
        }

19 View Source File : KService.cs
License : MIT License
Project Creator : AnotherEnd15

private static void KcpLog(IntPtr bytes, int len, IntPtr kcp, IntPtr user)
        {
            try
            {
                Marshal.Copy(bytes, logBuffer, 0, len);
                Log.Info(logBuffer.ToStr(0, len));
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }

19 View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static byte[] StructToByteArray(SmiObject message)
        {
            int size = Marshal.SizeOf(message);
            byte[] array = new byte[size];

            IntPtr pointer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(message, pointer, true);
            Marshal.Copy(pointer, array, 0, size);
            Marshal.FreeHGlobal(pointer);
            return array;
        }

19 View Source File : UnmanagedMemoryImageStream.cs
License : GNU General Public License v3.0
Project Creator : anydream

public int Read(byte[] buffer, int offset, int length) {
			if (length < 0)
				throw new IOException("Invalid size");
			length = (int)Math.Min(length, Length - Math.Min(Length, Position));
			Marshal.Copy(new IntPtr((byte*)owner.Address + currentAddr), buffer, offset, length);
			currentAddr += length;
			return length;
		}

19 View Source File : MemoryManager.cs
License : MIT License
Project Creator : Akaion

internal byte[] ReadVirtualMemory(IntPtr baseAddress, int bytesToRead)
        {
            var bytesBuffer = Marshal.AllocHGlobal(bytesToRead);
            
            if (!ReadProcessMemory(_processHandle, baseAddress, bytesBuffer, bytesToRead, IntPtr.Zero))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to read from a region of virtual memory in the remote process");
            }
            
            var bytesRead = new byte[bytesToRead];
            
            Marshal.Copy(bytesBuffer, bytesRead, 0, bytesToRead);
            
            Marshal.FreeHGlobal(bytesBuffer);

            return bytesRead;
        }

19 View Source File : OffscreenCEFClient.cs
License : MIT License
Project Creator : aleab

[SecurityCritical]
            protected override void OnPaint(CefBrowser browser, CefPaintElementType type, CefRectangle[] dirtyRects, IntPtr buffer, int width, int height)
            {
                if (browser != null)
                {
                    lock (sPixelLock)
                    {
                        if (browser != null)
                            Marshal.Copy(buffer, this.client.sPixelBuffer, 0, this.client.sPixelBuffer.Length);
                    }
                }
            }

19 View Source File : OVRNetwork.cs
License : MIT License
Project Creator : absurd-joy

public byte[] ToBytes()
		{
			int size = Marshal.SizeOf(this);
			Trace.replacedert(size == StructSize);

			byte[] arr = new byte[size];

			IntPtr ptr = Marshal.AllocHGlobal(size);
			Marshal.StructureToPtr(this, ptr, true);
			Marshal.Copy(ptr, arr, 0, size);
			Marshal.FreeHGlobal(ptr);
			return arr;
		}

19 View Source File : CommonMethods.cs
License : MIT License
Project Creator : alecgn

public static byte[] ConvertSecureStringToByteArray(SecureString secString)
        {
            var byteArray = new byte[secString.Length];
            var bstr = IntPtr.Zero;

            RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
                    delegate
                    {
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try { }
                        finally
                        {
                            bstr = Marshal.SecureStringToBSTR(secString);
                        }

                        Marshal.Copy(bstr, byteArray, 0, secString.Length);
                    },
                    delegate
                    {
                        if (bstr != IntPtr.Zero)
                        {
                            Marshal.ZeroFreeBSTR(bstr);
                            bstr = IntPtr.Zero;
                        }
                    },
                    null);

            return byteArray;
        }

19 View Source File : PackStub.cs
License : MIT License
Project Creator : AhmedMinegames

[STAThread]
        static void Main()
        {
            IntPtr NtdllModule = GetModuleHandle("ntdll.dll");
            IntPtr DbgUiRemoteBreakinAddress = GetProcAddress(NtdllModule, "DbgUiRemoteBreakin");
            IntPtr DbgUiConnectToDbgAddress = GetProcAddress(NtdllModule, "DbgUiConnectToDbg");
            byte[] Int3InvaildCode = { 0xCC };
            WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiRemoteBreakinAddress, Int3InvaildCode, 6, 0);
            WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiConnectToDbgAddress, Int3InvaildCode, 6, 0);
            IntPtr KernelModule = GetModuleHandle("kernel32.dll");
            IntPtr IsDebuggerPresentAddress = GetProcAddress(KernelModule, "IsDebuggerPresent");
            IntPtr CheckRemoteDebuggerPresentAddress = GetProcAddress(KernelModule, "CheckRemoteDebuggerPresent");
            byte[] Is_IsDebuggerPresentHooked = new byte[1];
            Marshal.Copy(IsDebuggerPresentAddress, Is_IsDebuggerPresentHooked, 0, 1);
            byte[] Is_CheckRemoteDebuggerPresentHooked = new byte[1];
            Marshal.Copy(CheckRemoteDebuggerPresentAddress, Is_CheckRemoteDebuggerPresentHooked, 0, 1);
            bool IsPresent = false;
            CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref IsPresent);
            if (IsDebuggerPresent() || Debugger.IsAttached || Debugger.IsLogging() || IsPresent || CloseHandleAntiDebug()) { Environment.Exit(0); }
            else
            {
                try
                {
                    StringBuilder DecryptEncryptionKey = new StringBuilder();
                    for (int c = 0; c < bPVkaPIHxmHs.Length; c++)
                        DecryptEncryptionKey.Append((char)((uint)bPVkaPIHxmHs[c] ^ (uint)Convert.FromBase64String("decryptkeyencryption")[c % 4]));
                    StringBuilder DecryptIV = new StringBuilder();
                    for (int c = 0; c < fCeZqcYnjRpl.Length; c++)
                        DecryptIV.Append((char)((uint)fCeZqcYnjRpl[c] ^ (uint)Convert.FromBase64String("decryptkeyiv")[c % 4]));
                    string sXQDBlJfKdPY = TqMIJUcgsXjVgxqJ(fMJUcafeoygb, DecryptEncryptionKey.ToString(), DecryptIV.ToString());
                    byte[] AzSLFXWvNQgp = Convert.FromBase64String(sXQDBlJfKdPY.Replace(".", "A").Replace("*", "B").Replace("_", @"S"));
                    replacedembly lnEFUxxAooHc = replacedembly.Load(AzSLFXWvNQgp);
                    lnEFUxxAooHc.EntryPoint.Invoke(null, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

19 View Source File : SensorNotifyIcon.cs
License : MIT License
Project Creator : AlexGyver

private Icon CreatePercentageIcon() {      
      try {
        graphics.Clear(Color.Transparent);
      } catch (ArgumentException) {
        graphics.Clear(Color.Black);
      }
      graphics.FillRectangle(darkBrush, 0.5f, -0.5f, bitmap.Width - 2, bitmap.Height);
      float value = sensor.Value.GetValueOrDefault();
      float y = 0.16f * (100 - value);
      graphics.FillRectangle(brush, 0.5f, -0.5f + y, bitmap.Width - 2, bitmap.Height - y);
      graphics.DrawRectangle(pen, 1, 0, bitmap.Width - 3, bitmap.Height - 1);

      BitmapData data = bitmap.LockBits(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
        ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
      byte[] bytes = new byte[bitmap.Width * bitmap.Height * 4];
      Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
      bitmap.UnlockBits(data);

      return IconFactory.Create(bytes, bitmap.Width, bitmap.Height, 
        PixelFormat.Format32bppArgb);
    }

19 View Source File : ImageUtils.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public static byte[] ToByteArray<T>(T obj)
                where T : struct
            {
                IntPtr ptr = IntPtr.Zero;
                try
                {
                    int size = Marshal.SizeOf(typeof(T));
                    ptr = Marshal.AllocHGlobal(size);
                    Marshal.StructureToPtr(obj, ptr, true);
                    byte[] bytes = new byte[size];
                    Marshal.Copy(ptr, bytes, 0, size);
                    return bytes;
                }
                finally
                {
                    if (ptr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(ptr);
                    }
                }
            }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ahuchjm

List<System.Drawing.Point> FindPicture(string subPic, string parPic, System.Drawing.Rectangle searchRect, byte errorRange, double matchRate = 0.9, bool isFindAll = false)
        {
            List<System.Drawing.Point> ListPoint = new List<System.Drawing.Point>();
            var subBitmap = new Bitmap(subPic);
            var parBitmap = new Bitmap(parPic);
            int subWidth = subBitmap.Width;
            int subHeight = subBitmap.Height;
            int parWidth = parBitmap.Width;
            int parHeight = parBitmap.Height;
            if (searchRect.IsEmpty)
            {
                searchRect = new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height);
            }

            var searchLeftTop = searchRect.Location;
            var searchSize = searchRect.Size;
            System.Drawing.Color startPixelColor = subBitmap.GetPixel(0, 0);
            var subData = subBitmap.LockBits(new System.Drawing.Rectangle(0, 0, subBitmap.Width, subBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var parData = parBitmap.LockBits(new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var byteArrarySub = new byte[subData.Stride * subData.Height];
            var byteArraryPar = new byte[parData.Stride * parData.Height];
            Marshal.Copy(subData.Scan0, byteArrarySub, 0, subData.Stride * subData.Height);
            Marshal.Copy(parData.Scan0, byteArraryPar, 0, parData.Stride * parData.Height);

            var iMax = searchLeftTop.Y + searchSize.Height - subData.Height;//行
            var jMax = searchLeftTop.X + searchSize.Width - subData.Width;//列

            int smallOffsetX = 0, smallOffsetY = 0;
            int smallStartX = 0, smallStartY = 0;
            int pointX = -1; int pointY = -1;
            for (int i = searchLeftTop.Y; i < iMax; i++)
            {
                for (int j = searchLeftTop.X; j < jMax; j++)
                {
                    //大图x,y坐标处的颜色值
                    int x = j, y = i;
                    int parIndex = i * parWidth * 4 + j * 4;
                    var colorBig = System.Drawing.Color.FromArgb(byteArraryPar[parIndex + 3], byteArraryPar[parIndex + 2], byteArraryPar[parIndex + 1], byteArraryPar[parIndex]);
                    ;
                    if (ColorAEqualColorB(colorBig, startPixelColor, errorRange))
                    {
                        smallStartX = x - smallOffsetX;//待找的图X坐标
                        smallStartY = y - smallOffsetY;//待找的图Y坐标
                        int sum = 0;//所有需要比对的有效点
                        int matchNum = 0;//成功匹配的点
                        for (int m = 0; m < subHeight; m++)
                        {
                            for (int n = 0; n < subWidth; n++)
                            {
                                int x1 = n, y1 = m;
                                int subIndex = m * subWidth * 4 + n * 4;
                                var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);

                                sum++;
                                int x2 = smallStartX + x1, y2 = smallStartY + y1;
                                int parReleativeIndex = y2 * parWidth * 4 + x2 * 4;//比对大图对应的像素点的颜色
                                var colorPixel = System.Drawing.Color.FromArgb(byteArraryPar[parReleativeIndex + 3], byteArraryPar[parReleativeIndex + 2], byteArraryPar[parReleativeIndex + 1], byteArraryPar[parReleativeIndex]);
                                if (ColorAEqualColorB(colorPixel, color, errorRange))
                                {
                                    matchNum++;
                                }
                            }
                        }
                        if ((double)matchNum / sum >= matchRate)
                        {
                            Console.WriteLine((double)matchNum / sum);
                            pointX = smallStartX + (int)(subWidth / 2.0);
                            pointY = smallStartY + (int)(subHeight / 2.0);
                            var point = new System.Drawing.Point(pointX, pointY);
                            if (!ListContainsPoint(ListPoint, point, 10))
                            {
                                ListPoint.Add(point);
                            }
                            if (!isFindAll)
                            {
                                goto FIND_END;
                            }
                        }
                    }
                    //小图x1,y1坐标处的颜色值
                }
            }
        FIND_END:
            subBitmap.UnlockBits(subData);
            parBitmap.UnlockBits(parData);
            subBitmap.Dispose();
            parBitmap.Dispose();
            GC.Collect();
            return ListPoint;
        }

19 View Source File : FirmwareTable.cs
License : MIT License
Project Creator : AlexGyver

public static byte[] GetTable(Provider provider, int table) {
      
      int size;
      try {
        size = NativeMethods.GetSystemFirmwareTable(provider, table, 
          IntPtr.Zero, 0);
      } catch (DllNotFoundException) { return null; } 
        catch (EntryPointNotFoundException) { return null; }

      if (size <= 0)
        return null;

      IntPtr nativeBuffer = Marshal.AllocHGlobal(size);
      NativeMethods.GetSystemFirmwareTable(provider, table, nativeBuffer, size);

      if (Marshal.GetLastWin32Error() != 0)
        return null;

      byte[] buffer = new byte[size];
      Marshal.Copy(nativeBuffer, buffer, 0, size);
      Marshal.FreeHGlobal(nativeBuffer);

      return buffer;
    }

private static Bitmap ConvolutionFilter(Bitmap sourceBitmap,
                                     double[,] filterMatrix,
                                          double factor = 1,
                                               int bias = 0,
                                     bool grayscale = false)
        {
            BitmapData sourceData =
                           sourceBitmap.LockBits(new Rectangle(0, 0,
                           sourceBitmap.Width, sourceBitmap.Height),
                                             ImageLockMode.ReadOnly,
                                        PixelFormat.Format32bppArgb);


            byte[] pixelBuffer = new byte[sourceData.Stride *
                                          sourceData.Height];


            byte[] resultBuffer = new byte[sourceData.Stride *
                                           sourceData.Height];


            Marshal.Copy(sourceData.Scan0, pixelBuffer, 0,
                                       pixelBuffer.Length);


            sourceBitmap.UnlockBits(sourceData);


            if (grayscale == true)
            {
                float rgb = 0;


                for (int k = 0; k < pixelBuffer.Length; k += 4)
                {
                    rgb = pixelBuffer[k] * 0.11f;
                    rgb += pixelBuffer[k + 1] * 0.59f;
                    rgb += pixelBuffer[k + 2] * 0.3f;


                    pixelBuffer[k] = (byte)rgb;
                    pixelBuffer[k + 1] = pixelBuffer[k];
                    pixelBuffer[k + 2] = pixelBuffer[k];
                    pixelBuffer[k + 3] = 255;
                }
            }


            double blue = 0.0;
            double green = 0.0;
            double red = 0.0;


            int filterWidth = filterMatrix.GetLength(1);
            int filterHeight = filterMatrix.GetLength(0);


            int filterOffset = (filterWidth - 1) / 2;
            int calcOffset = 0;


            int byteOffset = 0;


            for (int offsetY = filterOffset; offsetY <
                sourceBitmap.Height - filterOffset; offsetY++)
            {
                for (int offsetX = filterOffset; offsetX <
                    sourceBitmap.Width - filterOffset; offsetX++)
                {
                    blue = 0;
                    green = 0;
                    red = 0;


                    byteOffset = offsetY *
                                 sourceData.Stride +
                                 offsetX * 4;


                    for (int filterY = -filterOffset;
                        filterY <= filterOffset; filterY++)
                    {
                        for (int filterX = -filterOffset;
                            filterX <= filterOffset; filterX++)
                        {


                            calcOffset = byteOffset +
                                         (filterX * 4) +
                                         (filterY * sourceData.Stride);


                            blue += (double)(pixelBuffer[calcOffset]) *
                                    filterMatrix[filterY + filterOffset,
                                                 filterX + filterOffset];


                            green += (double)(pixelBuffer[calcOffset + 1]) *
                                     filterMatrix[filterY + filterOffset,
                                                  filterX + filterOffset];


                            red += (double)(pixelBuffer[calcOffset + 2]) *
                                   filterMatrix[filterY + filterOffset,
                                                filterX + filterOffset];
                        }
                    }


                    blue = factor * blue + bias;
                    green = factor * green + bias;
                    red = factor * red + bias;


                    if (blue > 255)
                    { blue = 255; }
                    else if (blue < 0)
                    { blue = 0; }


                    if (green > 255)
                    { green = 255; }
                    else if (green < 0)
                    { green = 0; }


                    if (red > 255)
                    { red = 255; }
                    else if (red < 0)
                    { red = 0; }


                    resultBuffer[byteOffset] = (byte)(blue);
                    resultBuffer[byteOffset + 1] = (byte)(green);
                    resultBuffer[byteOffset + 2] = (byte)(red);
                    resultBuffer[byteOffset + 3] = 255;
                }
            }


            Bitmap resultBitmap = new Bitmap(sourceBitmap.Width,
                                            sourceBitmap.Height);


            BitmapData resultData =
                       resultBitmap.LockBits(new Rectangle(0, 0,
                       resultBitmap.Width, resultBitmap.Height),
                                        ImageLockMode.WriteOnly,
                                    PixelFormat.Format32bppArgb);


            Marshal.Copy(resultBuffer, 0, resultData.Scan0,
                                       resultBuffer.Length);
            resultBitmap.UnlockBits(resultData);


            return resultBitmap;
        }

19 View Source File : MarshalUTF8.cs
License : Apache License 2.0
Project Creator : AlexWan

public static String PtrToStringUtf8(IntPtr pData)
        {
            // this is just to get buffer length in bytes
            String errStr = Marshal.PtrToStringAnsi(pData);
            int length = errStr.Length;

            Byte[] data = new byte[length];
            Marshal.Copy(pData, data, 0, length);

            return _utf8.GetString(data);
        }

19 View Source File : RawInput.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public byte[] data(int index)
		{
			byte[] result = new byte[1];
			if (((dwCount > 0) && (index < dwSizeHID)))
			{
				result = new byte[dwCount];
				Marshal.Copy(pData, result, Convert.ToInt32(index * dwCount), dwCount);
			}
			return result;
		}

19 View Source File : StringConverter.cs
License : MIT License
Project Creator : AlternateLife

public static string PointerToString(IntPtr pointer, bool freePointer = true)
        {
            if (pointer == IntPtr.Zero)
            {
                return null;
            }

            var length = 0;

            while (Marshal.ReadByte(pointer, length) != 0)
            {
                ++length;
            }

            var buffer = new byte[length];
            Marshal.Copy(pointer, buffer, 0, buffer.Length);

            if (freePointer)
            {
                Rage.FreeArray(pointer);
            }

            return Encoding.UTF8.GetString(buffer);
        }

19 View Source File : WebPNative.cs
License : MIT License
Project Creator : 0xC0000054

[System.Diagnostics.Codereplacedysis.SuppressMessage(
                "Microsoft.Design",
                "CA1031:DoNotCatchGeneralExceptionTypes",
                Justification = "The exception will be re-thrown after WebPSave returns the error code.")]
            public WebPEncodingError WriteImageCallback(IntPtr image, UIntPtr imageSize)
            {
                if (image == IntPtr.Zero)
                {
                    return WebPEncodingError.NullParameter;
                }

                if (imageSize == UIntPtr.Zero)
                {
                    // Ignore zero-length images.
                    return WebPEncodingError.Ok;
                }

                // 81920 is the largest multiple of 4096 that is below the large object heap threshold.
                const int MaxBufferSize = 81920;

                try
                {
                    long size = checked((long)imageSize.ToUInt64());

                    int bufferSize = (int)Math.Min(size, MaxBufferSize);

                    byte[] streamBuffer = new byte[bufferSize];

                    output.SetLength(size);

                    long offset = 0;
                    long remaining = size;

                    while (remaining > 0)
                    {
                        int copySize = (int)Math.Min(MaxBufferSize, remaining);

                        Marshal.Copy(new IntPtr(image.ToInt64() + offset), streamBuffer, 0, copySize);

                        output.Write(streamBuffer, 0, copySize);

                        offset += copySize;
                        remaining -= copySize;
                    }
                }
                catch (OperationCanceledException)
                {
                    return WebPEncodingError.UserAbort;
                }
                catch (Exception ex)
                {
                    WriteException = ex;
                    return WebPEncodingError.BadWrite;
                }

                return WebPEncodingError.Ok;
            }

19 View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis

static byte[] convert_uint8_numpy_array_to_byte_array(dynamic d) {
      // See also: https://github.com/yagweb/pythonnetLab/blob/master/pynetLab/Numpy.cs
      var d_len = (int)d.nbytes;
      var buffer = new byte[d_len];      
      var meta = d.GetAttr("__array_interface__");
      var address = new System.IntPtr((long)meta["data"][0]);
      System.Runtime.InteropServices.Marshal.Copy(address, buffer, 0, d_len);
      return buffer;
    }

19 View Source File : SharedMemory.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public byte[] GetData(int millisecondsTimeout = Timeout.Infinite)
		{
			byte[] buffer = null;
			this.MutexInvoke(() =>
			{
				int size = Marshal.ReadInt32(this._memory, 4);
				buffer = new byte[size];

				IntPtr pData = new IntPtr(this._memory.ToInt64() + 8);
				Marshal.Copy(pData, buffer, 0, buffer.Length);

			}, millisecondsTimeout);
			return buffer;
		}

19 View Source File : CCBPayUtil.cs
License : Apache License 2.0
Project Creator : anjoy8

internal static byte[] GetRSAFromDER(byte[] DERData)
		{
			byte[] array = null;
			byte[] array2 = null;
			uint num = 0U;
			IntPtr zero = IntPtr.Zero;
			if (!RSACryptoServiceProviderExtension.CryptDecodeObject((RSACryptoServiceProviderExtension.CRYPT_ENCODING_FLAGS)65537U, new IntPtr(8), DERData, (uint)DERData.Length, RSACryptoServiceProviderExtension.CRYPT_DECODE_FLAGS.NONE, array, ref num))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error());
			}
			array = new byte[num];
			if (RSACryptoServiceProviderExtension.CryptDecodeObject((RSACryptoServiceProviderExtension.CRYPT_ENCODING_FLAGS)65537U, new IntPtr(8), DERData, (uint)DERData.Length, RSACryptoServiceProviderExtension.CRYPT_DECODE_FLAGS.NONE, array, ref num))
			{
				GCHandle gchandle = GCHandle.Alloc(array, GCHandleType.Pinned);
				try
				{
					RSACryptoServiceProviderExtension.CERT_PUBLIC_KEY_INFO cert_PUBLIC_KEY_INFO = (RSACryptoServiceProviderExtension.CERT_PUBLIC_KEY_INFO)Marshal.PtrToStructure(gchandle.AddrOfPinnedObject(), typeof(RSACryptoServiceProviderExtension.CERT_PUBLIC_KEY_INFO));
					array2 = new byte[cert_PUBLIC_KEY_INFO.PublicKey.cbData];
					Marshal.Copy(cert_PUBLIC_KEY_INFO.PublicKey.pbData, array2, 0, array2.Length);
				}
				finally
				{
					gchandle.Free();
				}
				return array2;
			}
			throw new Win32Exception(Marshal.GetLastWin32Error());
		}

19 View Source File : AudioFile.cs
License : MIT License
Project Creator : adlez27

public bool RecordProcedure(int Handle, IntPtr Buffer, int Length, IntPtr User)
        {
            byte[] temp = new byte[Length];
            Marshal.Copy(Buffer, temp, 0, Length);

            //Modify recording according to Input Volume
            short[] sdata = new short[temp.Length/2];
            System.Buffer.BlockCopy(temp, 0, sdata, 0, temp.Length);
            for (var i = 0; i < sdata.Length; i++)
            {
                sdata[i] = (short)(sdata[i] * ((double)settings.AudioInputLevel / 100.0));
            }
            System.Buffer.BlockCopy(sdata, 0, temp, 0, temp.Length);

            data.AddRange(temp);
            return true;
        }

19 View Source File : KChannel.cs
License : MIT License
Project Creator : AnotherEnd15

public void Output(IntPtr bytes, int count)
		{
			if (this.IsDisposed)
			{
				return;
			}
			try
			{
				// 没连接上 kcp不往外发消息, 其实本来没连接上不会调用update,这里只是做一层保护
				if (!this.IsConnected)
				{
					return;
				}
				
				if (count == 0)
				{
					Log.Error($"output 0");
					return;
				}

				byte[] buffer = this.sendCache;
				buffer.WriteTo(0, KcpProtocalType.MSG);
				// 每个消息头部写下该channel的id;
				buffer.WriteTo(1, this.LocalConn);
				Marshal.Copy(bytes, buffer, 5, count);
				this.socket.SendTo(buffer, 0, count + 5, SocketFlags.None, this.RemoteAddress);
			}
			catch (Exception e)
			{
				Log.Error(e);
				this.OnError(ErrorCode.ERR_SocketCantSend);
			}
		}

19 View Source File : Scanner.cs
License : Apache License 2.0
Project Creator : airbus-cert

internal List<ScanResult> ScanMemory(
            IntPtr buffer,
            int length,
            CompiledRules rules,
            YR_SCAN_FLAGS flags)
        {
            byte[] res = new byte[length - 1];
            Marshal.Copy(buffer, res, 0, length);
            return ScanMemory(ref res, length, rules, flags);
        }

19 View Source File : AquesTalk.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void TextToWave(
            string textToSpeak,
            string waveFileName,
            AQTK_VOICE voice)
        {
            if (string.IsNullOrWhiteSpace(textToSpeak))
            {
                return;
            }

            if (this.SyntheDelegate == null ||
                this.FreeWaveDelegate == null)
            {
                return;
            }

            var wavePtr = IntPtr.Zero;
            var waveSize = 0;

            try
            {
                var chars = this.UTF16Encoding.GetBytes(textToSpeak);

                // テキストを音声データに変換する
                wavePtr = this.SyntheDelegate?.Invoke(
                    ref voice,
                    chars,
                    ref waveSize) ?? IntPtr.Zero;

                if (wavePtr == IntPtr.Zero ||
                    waveSize <= 0)
                {
                    return;
                }

                FileHelper.CreateDirectory(waveFileName);

                // 生成したwaveデータを読み出す
                var buff = new byte[waveSize];
                Marshal.Copy(wavePtr, buff, 0, (int)waveSize);
                using (var fs = new FileStream(waveFileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buff, 0, buff.Length);
                }
            }
            finally
            {
                if (wavePtr != IntPtr.Zero &&
                    waveSize != 0)
                {
                    this.FreeWaveDelegate?.Invoke(wavePtr);
                }
            }
        }

19 View Source File : HeifStreamWriter.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054

protected override void WriteCore(IntPtr data, long count)
        {
            long offset = 0;
            long remaining = count;

            while (remaining > 0)
            {
                int copySize = (int)Math.Min(MaxWriteBufferSize, remaining);

                Marshal.Copy(new IntPtr(data.ToInt64() + offset), this.streamBuffer, 0, copySize);

                this.stream.Write(this.streamBuffer, 0, copySize);

                offset += copySize;
                remaining -= copySize;
            }
        }

19 View Source File : UnmanagedMemoryImageStream.cs
License : GNU General Public License v3.0
Project Creator : anydream

public unsafe byte[] ReadBytes(int size) {
			if (size < 0)
				throw new IOException("Invalid size");
			size = (int)Math.Min(size, Length - Math.Min(Length, Position));
			var newData = new byte[size];
			Marshal.Copy(new IntPtr((byte*)owner.Address + currentAddr), newData, 0, size);
			currentAddr += size;
			return newData;
		}

19 View Source File : MethodDetour.cs
License : MIT License
Project Creator : Akaion

private void PrepareDetour()
        {
            // Ensure both methods are JIT compiled
            
            RuntimeHelpers.PrepareMethod(_originalMethodHandle);

            RuntimeHelpers.PrepareMethod(_targetMethodHandle);

            // Construct the shellcode needed to detour the method
            
            var shellcode = new List<byte>();
            
            if (Environment.Is64BitProcess)
            {
                // mov rax, targetMethodAddress
                
                shellcode.AddRange(new byte[] {0x48, 0xB8});
                
                shellcode.AddRange(BitConverter.GetBytes((long) _targetMethodHandle.GetFunctionPointer()));
                
                // jmp rax
                
                shellcode.AddRange(new byte[] {0xFF, 0xE0});
            }

            else
            {
                // mov eax, targetMethodAddress
                
                shellcode.Add(0xB8);
                
                shellcode.AddRange(BitConverter.GetBytes((int) _targetMethodHandle.GetFunctionPointer()));
                
                // jmp eax
                
                shellcode.AddRange(new byte[] {0xFF, 0xE0});
            }

            _detourBytes = shellcode.ToArray();
            
            // Save the bytes of the original method
            
            _originalMethodBytes = new byte[_detourBytes.Length];
            
            Marshal.Copy(_originalMethodHandle.GetFunctionPointer(), _originalMethodBytes, 0, _detourBytes.Length);
        }

19 View Source File : ZFrame.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public override int Read(byte[] buffer, int offset, int count)
        {
            int remaining = Math.Min(count, Math.Max(0, (int)(Length - position)));
            if (remaining == 0)
            {
                return 0;
            }
            if (remaining < 0)
            {
                return -1;
            }
            Marshal.Copy(DataPtr() + position, buffer, offset, (int)remaining);

            position += remaining;
            return remaining;
        }

19 View Source File : UiHelper.GameFunctions.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public static T* CloneNode<T>(T* original) where T : unmanaged {
            var allocation = Clereplacedloc<T>();

            var bytes = new byte[sizeof(T)];
            Marshal.Copy(new IntPtr(original), bytes, 0, bytes.Length);
            Marshal.Copy(bytes, 0, new IntPtr(allocation), bytes.Length);

            var newNode = (AtkResNode*)allocation;
            newNode->ParentNode = null;
            newNode->ChildNode = null;
            newNode->ChildCount = 0;
            newNode->PrevSiblingNode = null;
            newNode->NextSiblingNode = null;
            return allocation;
        }

19 View Source File : StreamIOCallbacks.cs
License : MIT License
Project Creator : 0xC0000054

public unsafe int Write(IntPtr buffer, uint count, uint* bytesWritten)
        {
            if (bytesWritten != null)
            {
                *bytesWritten = 0;
            }

            if (count == 0)
            {
                return HResult.S_OK;
            }

            try
            {
                long offset = 0;
                long remaining = count;

                do
                {
                    int copySize = (int)Math.Min(MaxBufferSize, remaining);

                    Marshal.Copy(new IntPtr(buffer.ToInt64() + offset), this.streamBuffer, 0, copySize);

                    this.stream.Write(this.streamBuffer, 0, copySize);

                    offset += copySize;
                    remaining -= copySize;

                } while (remaining > 0);

                if (bytesWritten != null)
                {
                    *bytesWritten = count;
                }

                return HResult.S_OK;
            }
            catch (Exception ex)
            {
                this.CallbackExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                return ex.HResult;
            }
        }

public static void doSomethingWithBitmapFast(System.Drawing.Bitmap bmp)
        {
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

            System.Drawing.Imaging.BitmapData bmpData =
                bmp.LockBits(rect,
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    bmp.PixelFormat);

            IntPtr ptr = bmpData.Scan0;

            int bytes = bmpData.Stride * bmp.Height;
            byte[] rgbValues = new byte[bytes];

            System.Runtime.InteropServices.Marshal.Copy(ptr,
                           rgbValues, 0, bytes);

            byte red = 0;
            byte green = 0;
            byte blue = 0;

            for (int x = 0; x < bmp.Width; x++)
            {
                for (int y = 0; y < bmp.Height; y++)
                {
                    //See the link above for an explanation 
                    //of this calculation
                    int position = (y * bmpData.Stride) + (x * Image.GetPixelFormatSize(bmpData.PixelFormat) / 8);
                    blue = rgbValues[position];
                    green = rgbValues[position + 1];
                    red = rgbValues[position + 2];
                    Console.WriteLine("Fast: " + red + " "
                                       + green + " " + blue);
                }
            }
            bmp.UnlockBits(bmpData);
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ahuchjm

System.Drawing.Point FindColor(string parPic, string searchColor, System.Drawing.Rectangle searchRect, byte errorRange = 10)
        {
            var colorX = System.Drawing.ColorTranslator.FromHtml(searchColor);
            var parBitmap = new Bitmap(parPic);
            var parData = parBitmap.LockBits(new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var byteArraryPar = new byte[parData.Stride * parData.Height];
            Marshal.Copy(parData.Scan0, byteArraryPar, 0, parData.Stride * parData.Height);
            if (searchRect.IsEmpty)
            {
                searchRect = new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height);
            }
            var searchLeftTop = searchRect.Location;
            var searchSize = searchRect.Size;
            var iMax = searchLeftTop.Y + searchSize.Height;//行
            var jMax = searchLeftTop.X + searchSize.Width;//列
            int pointX = -1; int pointY = -1;
            for (int m = searchRect.Y; m < iMax; m++)
            {
                for (int n = searchRect.X; n < jMax; n++)
                {
                    int index = m * parBitmap.Width * 4 + n * 4;
                    var color = System.Drawing.Color.FromArgb(byteArraryPar[index + 3], byteArraryPar[index + 2], byteArraryPar[index + 1], byteArraryPar[index]);
                    if (ColorAEqualColorB(color, colorX, errorRange))
                    {
                        pointX = n;
                        pointY = m;
                        goto END;
                    }
                }
            }
        END:
            parBitmap.UnlockBits(parData);
            return new System.Drawing.Point(pointX, pointY);
        }

19 View Source File : SensorNotifyIcon.cs
License : MIT License
Project Creator : AlexGyver

private Icon CreateTransparentIcon() {
      string text = GetString();
      int count = 0;
      for (int i = 0; i < text.Length; i++)
        if ((text[i] >= '0' && text[i] <= '9') || text[i] == '-')
          count++;
      bool small = count > 2;

      graphics.Clear(Color.Black);
      TextRenderer.DrawText(graphics, text, small ? smallFont : font,
        new Point(-2, small ? 1 : 0), Color.White, Color.Black);        

      BitmapData data = bitmap.LockBits(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
        ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

      IntPtr Scan0 = data.Scan0;

      int numBytes = bitmap.Width * bitmap.Height * 4;
      byte[] bytes = new byte[numBytes];
      Marshal.Copy(Scan0, bytes, 0, numBytes);
      bitmap.UnlockBits(data);

      byte red, green, blue;
      for (int i = 0; i < bytes.Length; i += 4) {
        blue = bytes[i];
        green = bytes[i + 1];
        red = bytes[i + 2];

        bytes[i] = color.B;
        bytes[i + 1] = color.G;
        bytes[i + 2] = color.R;
        bytes[i + 3] = (byte)(0.3 * red + 0.59 * green + 0.11 * blue);
      }

      return IconFactory.Create(bytes, bitmap.Width, bitmap.Height, 
        PixelFormat.Format32bppArgb);
    }

See More Examples