public override ARESULT Initialize(Dictionary <string, object> arguments) { device = arguments["device"] as IDevice; // 读取配置信息 if (!device.Read(ReadMode.IrCameraParameters, null, out object outData, out _)) { return(ARESULT.E_INVALIDARG); } // 创建资源 Repository.Entities.Configuration.IrCameraParameters irCameraParameters = outData as Repository.Entities.Configuration.IrCameraParameters; temperature = PinnedBuffer <float> .Alloc(irCameraParameters.temperatureWidth *irCameraParameters.temperatureHeight); irImage = PinnedBuffer <byte> .Alloc(irCameraParameters.width *irCameraParameters.height * 3 / 2); tempertureDuration = 1000 / irCameraParameters.temperatureFrameRate; // 读取配置信息 if (!device.Read(ReadMode.CameraParameters, null, out outData, out _)) { return(ARESULT.E_INVALIDARG); } // 创建资源 Repository.Entities.Configuration.CameraParameters cameraParameters = outData as Repository.Entities.Configuration.CameraParameters; image = PinnedBuffer <byte> .Alloc(cameraParameters.width *cameraParameters.height * 3 / 2); videoDuration = 1000 / cameraParameters.videoFrameRate; return(base.Initialize(arguments)); }
static void Main(string[] args) { Console.WriteLine("ZMQ version = " + ZMQ.GetVersionString()); IntPtr zmqContext = ZMQ.zmq_ctx_new(); IntPtr requestSocket = ZMQ.zmq_socket(zmqContext, ZMQ.ZMQ_REQ); using (var endpoint = ASCII("tcp://localhost:60000")) { ZMQ.zmq_connect(requestSocket, endpoint); String msg = "Hello, World!"; if (args.Length > 0) { msg = args[0]; } using (var buffer = ASCII(msg)) ZMQ.zmq_send(requestSocket, buffer, buffer.Length, 0); String text; using (var buffer = new PinnedBuffer(new byte[64])) { ZMQ.zmq_recv(requestSocket, buffer, buffer.Length, 0); text = Encoding.ASCII.GetString(buffer); } Console.WriteLine(text); } ZMQ.zmq_close(requestSocket); ZMQ.zmq_ctx_term(zmqContext); }
protected override void Run() { PinnedBuffer <byte> image = null; int size = width * height; while (!IsTerminated()) { // 克隆数据 var temp = this.image; if (temp == null) { Thread.Sleep(duration); continue; } try { // 编码 image = Arrays.Clone(temp, image, sizeof(byte)); encoder.Encode(image.ptr, image.ptr + size, image.ptr + size + size / 4); } catch (Exception e) { Tracker.LogE(e); } Thread.Sleep(duration); } }
private PinnedBuffer EncryptInCbcMode(PinnedBuffer plaintext, PinnedBuffer privateKey, PinnedBuffer initializationVector) { initializationVector.RejectIf().IsNull(nameof(initializationVector)).OrIf(argument => argument.Count() != BlockSizeInBytes, nameof(privateKey), "The length of the specified initialization vector is invalid for the algorithm."); using (var encryptionProvider = InitializeProvider()) { encryptionProvider.BlockSize = BlockSizeInBits; encryptionProvider.KeySize = KeySizeInBits; encryptionProvider.Mode = Mode; encryptionProvider.Padding = PaddingMode; encryptionProvider.Key = privateKey; encryptionProvider.IV = initializationVector; using (var encryptor = encryptionProvider.CreateEncryptor(privateKey, initializationVector)) { using (var memoryStream = new MemoryStream()) { using (var cryptographicStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptographicStream.Write(plaintext, 0, plaintext.Length); cryptographicStream.FlushFinalBlock(); return(new PinnedBuffer(initializationVector.Concat(memoryStream.ToArray()).ToArray(), false)); } } } } }
public static SnappyStatus snappy_validate_compressed_buffer(byte[] input, int input_offset, int input_length) { using (var pinnedInput = new PinnedBuffer(input, input_offset)) { return(SnappyNativeMethodsAdapter.snappy_validate_compressed_buffer(pinnedInput.IntPtr, input_length)); } }
private PinnedBuffer DecryptInCbcMode(PinnedBuffer ciphertext, PinnedBuffer privateKey) { using (var initializationVector = new PinnedBuffer(BlockSizeInBytes, true)) { Array.Copy(ciphertext, 0, initializationVector, 0, BlockSizeInBytes); using (var cipherTextSansInitializationVector = new PinnedBuffer((ciphertext.Length - BlockSizeInBytes), true)) { Array.Copy(ciphertext, BlockSizeInBytes, cipherTextSansInitializationVector, 0, cipherTextSansInitializationVector.Length); using (var encryptionProvider = InitializeProvider()) { encryptionProvider.BlockSize = BlockSizeInBits; encryptionProvider.KeySize = KeySizeInBits; encryptionProvider.Mode = Mode; encryptionProvider.Padding = PaddingMode; encryptionProvider.Key = privateKey; encryptionProvider.IV = initializationVector; using (var decryptor = encryptionProvider.CreateDecryptor(privateKey, initializationVector)) { using (var memoryStream = new MemoryStream()) { using (var cryptographicStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write)) { cryptographicStream.Write(cipherTextSansInitializationVector, 0, cipherTextSansInitializationVector.Length); cryptographicStream.FlushFinalBlock(); return(new PinnedBuffer(memoryStream.ToArray(), false)); } } } } } } }
/// <inheritdoc /> internal override void Apply(float[] scanlineBuffer, int scanlineWidth, int offset, int x, int y) { Guard.MustBeGreaterThanOrEqualTo(scanlineBuffer.Length, offset + scanlineWidth, nameof(scanlineWidth)); using (PinnedBuffer <float> buffer = new PinnedBuffer <float>(scanlineBuffer)) { BufferSpan <float> slice = buffer.Slice(offset); for (int xPos = 0; xPos < scanlineWidth; xPos++) { int targetX = xPos + x; int targetY = y; float opacity = slice[xPos]; if (opacity > Constants.Epsilon) { Vector4 backgroundVector = this.Target[targetX, targetY].ToVector4(); // 2d array index at row/column Vector4 sourceVector = this.patternVector[targetY % this.patternVector.Height, targetX % this.patternVector.Width]; Vector4 finalColor = Vector4BlendTransforms.PremultipliedLerp(backgroundVector, sourceVector, opacity); TColor packed = default(TColor); packed.PackFromVector4(finalColor); this.Target[targetX, targetY] = packed; } } } }
static void PublishLoop(SWIGTYPE_p_void pubSocket) { String last = String.Empty; int seed = (int)DateTime.Now.Ticks; //narrowing (discard MSBs) var rnd = new Random(seed); var symbols = new String[] { "MSFT", "GOOG", "TSLA", "AMZN", "NVDA", "FB", "PS" }; var lastBidPrice = new double[] { 96.71, 1065.13, 277.76, 1571.05, 240.28, 182.50, 19.94 }; var throttle = TimeSpan.FromMilliseconds(100); //~10 msgs/s while (true) { int i = rnd.Uniform(0, symbols.Length); var symbol = symbols[i]; //var bidPrice = lastBidPrice[i] + (lastBidPrice[i] * rnd.Uniform(-0.0125, 0.0125)); var bidPrice = lastBidPrice[i] + (lastBidPrice[i] * (rnd.Gaussian() / 100.0)); lastBidPrice[i] = bidPrice; var quantity = rnd.Uniform(50, 1000 + 1); var tradeType = (MarketOrder.TypeOfTrade)rnd.Uniform(1, 5 + 1); var timestamp = DateTime.Now; var order = new MarketOrder(symbol, bidPrice, quantity, tradeType, timestamp); using (var buffer = new PinnedBuffer(MarketOrder.ToBytes(order))) { if (-1 != ZeroMQ.zmq_send(pubSocket, buffer, buffer.Length, 0)) { last = String.Format("Success: Message [{0}] sent", order); } else { last = String.Format("Warning: Message [{0}] not sent", order); } Console.WriteLine(last); Thread.Sleep(throttle); } } }
public void OverwriteWithZeros_ShouldProduceDesiredResults_UsingFieldConstructor() { // Arrange. var length = 8; var field = new Byte[length]; using (var target = new PinnedBuffer(field, false)) { // Arrange. target[0] = 0x01; target[2] = 0x01; target[4] = 0x01; target[6] = 0x01; // Assert. field[0].Should().Be(0x01); field[2].Should().Be(0x01); field[4].Should().Be(0x01); field[6].Should().Be(0x01); // Act. target.OverwriteWithZeros(); // Assert. target.Should().OnlyContain(value => value == 0x00); field.Should().OnlyContain(value => value == 0x00); } }
public void FunctionalLifeSpanTest_ShouldProduceDesiredResults_UsingLengthConstructor() { // Arrange. var length = 8; var field = (Byte[])null; using (var target = new PinnedBuffer(length, true)) { // Arrange. field = target; // Assert. ReferenceEquals(field, target).Should().BeFalse(); target.Length.Should().Be(length); field.Should().NotBeNull(); field.Length.Should().Be(length); field.Should().OnlyContain(value => value == 0x00); // Act. target[5] = 0x4a; target[3] = 0xf6; // Assert. field[1].Should().Be(0x00); field[3].Should().Be(0xf6); field[5].Should().Be(0x4a); } // Assert. field.Should().OnlyContain(value => value == 0x00); }
static void PublishLoop(SWIGTYPE_p_void pubSocket) { int count = 0; string last = String.Empty; //, title = Console.Title; var throttle = TimeSpan.FromMilliseconds(100); //~10 msgs/s while (true) { String msg = "MSG #" + (++count); using (var buffer = PinnedBuffer.ASCII(msg.PadRight(16, ' '))) { if (-1 != ZeroMQ.zmq_send(pubSocket, buffer, buffer.Length, 0)) { last = String.Format("Success: Message [{0}] sent", msg); } else { last = String.Format("Warning: Message [{0}] not sent", msg); } //Console.Title = String.Format("{0}[{1}]", title, last); Console.WriteLine(last); Thread.Sleep(throttle); } } }
public void Dispose() { PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(42); buffer.Dispose(); Assert.True(buffer.IsDisposedOrLostArrayOwnership); }
public static SnappyStatus snappy_uncompress(byte[] input, int input_offset, int input_length, byte[] output, int output_offset, ref int output_length) { using (var pinnedInput = new PinnedBuffer(input, input_offset)) using (var pinnedOutput = new PinnedBuffer(output, output_offset)) { return(SnappyNativeMethodsAdapter.snappy_uncompress(pinnedInput.IntPtr, input_length, pinnedOutput.IntPtr, ref output_length)); } }
/// <summary> /// Generates a new <see cref="SecureSymmetricKey" />. /// </summary> /// <param name="algorithm"> /// The symmetric-key algorithm that the generated key is derived to interoperate with. The default value is /// <see cref="SymmetricAlgorithmSpecification.Aes256Cbc" />. /// </param> /// <param name="derivationMode"> /// The mode used to derive the generated key. The default value is /// <see cref="SecureSymmetricKeyDerivationMode.XorLayeringWithSubstitution" />. /// </param> /// <returns> /// A new <see cref="SecureSymmetricKey" />. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="algorithm" /> is equal to <see cref="SymmetricAlgorithmSpecification.Unspecified" /> or /// <paramref name="derivationMode" /> is equal to <see cref="SecureSymmetricKeyDerivationMode.Unspecified" />. /// </exception> public static SecureSymmetricKey New(SymmetricAlgorithmSpecification algorithm, SecureSymmetricKeyDerivationMode derivationMode) { using (var keySource = new PinnedBuffer(KeySourceLengthInBytes, true)) { RandomnessProvider.GetBytes(keySource); return(New(algorithm, derivationMode, keySource)); } }
public WaveOut( int deviceID, short channels, int samplesPerSecond, SPEAKER channelMask, Guid formatSubType, ILoggerFactory loggerFactory, ElapsedTimeCounter counter, ITargetBlock <PcmBuffer <T> > releaseQueue ) { _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); _counter = counter ?? throw new ArgumentNullException(nameof(counter)); ArgumentNullException.ThrowIfNull(releaseQueue); _logger = _loggerFactory.CreateLogger <WaveOut <T> >(); _headerPool = new BufferPool <WaveHeaderBuffer>(1, () => { return(new WaveHeaderBuffer()); }, _loggerFactory); _driverCallBack = new PinnedDelegate <DriverCallBack.Proc>(new DriverCallBack.Proc(DriverCallBackProc)); var format = new WaveFormatExtensible(); format.wfe.formatType = WaveFormatEx.FORMAT.EXTENSIBLE; format.wfe.channels = (ushort)channels; format.wfe.samplesPerSecond = (uint)samplesPerSecond; format.wfe.bitsPerSample = (ushort)(SIZE_OF_T * 8); format.wfe.blockAlign = (ushort)(format.wfe.channels * format.wfe.bitsPerSample / 8); format.wfe.averageBytesPerSecond = format.wfe.samplesPerSecond * format.wfe.blockAlign; format.wfe.size = (ushort)(Marshal.SizeOf <WaveFormatExtensiblePart>()); format.exp.validBitsPerSample = format.wfe.bitsPerSample; format.exp.channelMask = ToSPEAKER(channelMask); format.exp.subFormat = formatSubType; //たまに失敗するので、ピン止めしておく using var formatPin = new PinnedBuffer <WaveFormatExtensible>(format); var mmResult = NativeMethods.waveOutOpen( out _handle, deviceID, ref format, _driverCallBack.FunctionPointer, IntPtr.Zero, ( DriverCallBack.TYPE.FUNCTION | DriverCallBack.TYPE.WAVE_FORMAT_DIRECT ) ); if (mmResult != MMRESULT.NOERROR) { throw new WaveException(mmResult); } _releaseAction = new TransformBlock <IntPtr, PcmBuffer <T> >(headerPtr => Unprepare(headerPtr)); _releaseAction.LinkTo(releaseQueue); }
/// <summary> /// 保存图像 /// </summary> /// <param name="image">图像</param> /// <returns>是否成功</returns> public static string SaveYV12Image(PinnedBuffer <byte> image) { if (image == null) { return(null); } return(SaveYV12Image(image.width, image.height, image.buffer)); }
static void Main(String[] args) { Console.WriteLine("ZMQ version = {0}", Utils.GetZmqVersion()); var ctx = ZeroMQ.zmq_ctx_new(); if (ctx != null) { var requestSocket = ZeroMQ.zmq_socket(ctx, ZeroMQ.ZMQ_REQ); if (requestSocket != null) { if (-1 != ZeroMQ.zmq_connect(requestSocket, "tcp://localhost:60000")) { String msg = 0 == args.Length ? "Hello World" : args[0].Substring(0, Math.Min(args[0].Length, 64)); using (var buffer = PinnedBuffer.ASCII(msg)) { if (-1 != ZeroMQ.zmq_send(requestSocket, buffer, buffer.Length, 0)) { Console.WriteLine(msg + " sent"); if (-1 != ZeroMQ.zmq_recv(requestSocket, buffer, buffer.Length, 0)) { Console.WriteLine(PinnedBuffer.ASCII(buffer) + " received back"); } else { Console.WriteLine("receive back failed"); } } else { Console.WriteLine("send failed"); } } } else { Console.WriteLine("connect failed"); } ZeroMQ.zmq_close(requestSocket); } else { Console.WriteLine("socket failed"); } ZeroMQ.zmq_ctx_term(ctx); } else { Console.WriteLine("context failed"); } }
public static SnappyStatus snappy_uncompressed_length(byte[] input, int input_offset, int input_length, out int output_length) { SnappyStatus status; using (var pinnedInput = new PinnedBuffer(input, input_offset)) { status = Snappy64NativeMethods.snappy_uncompressed_length(pinnedInput.IntPtr, (ulong)input_length, out var ulongOutput_length); output_length = (int)ulongOutput_length; } return(status); }
public void Read(int length, int index) { Foo[] a = Foo.CreateArray(length); using (PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(a)) { Foo element = buffer[index]; Assert.Equal(a[index], element); } }
public void Write(int length, int index) { Foo[] a = Foo.CreateArray(length); using (PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(a)) { buffer[index] = new Foo(666, 666); Assert.Equal(new Foo(666, 666), a[index]); } }
static void Main(String[] args) { Console.WriteLine("ZMQ version = {0}", Utils.GetZmqVersion()); var ctx = ZeroMQ.zmq_ctx_new(); if (ctx != null) { var replySocket = ZeroMQ.zmq_socket(ctx, ZeroMQ.ZMQ_REP); if (replySocket != null) { if (0 == ZeroMQ.zmq_bind(replySocket, "tcp://*:60000")) { using (var buffer = new PinnedBuffer(new byte[64])) { if (-1 != ZeroMQ.zmq_recv(replySocket, buffer, buffer.Length, 0)) { String msg = PinnedBuffer.ASCII(buffer).Replace('\0', ' ').TrimEnd(); Console.WriteLine(msg + " received"); if (-1 != ZeroMQ.zmq_send(replySocket, buffer, buffer.Length, 0)) { Console.WriteLine(msg + " sent back"); } else { Console.WriteLine("send failed"); } } else { Console.WriteLine("receive failed"); } } } else { Console.WriteLine("bind failed"); } ZeroMQ.zmq_close(replySocket); } else { Console.WriteLine("socket failed"); } ZeroMQ.zmq_ctx_term(ctx); } else { Console.WriteLine("context failed"); } }
/// <summary> /// Initializes a new instance of the <see cref="SecureBuffer" /> class. /// </summary> /// <param name="length"> /// The length of the buffer, in bytes. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="length" /> is less than or equal to zero. /// </exception> public SecureBuffer(Int32 length) : base(ConcurrencyControlMode.SingleThreadLock) { Length = length.RejectIf().IsLessThanOrEqualTo(0, nameof(length)); Entropy = new PinnedBuffer(EntropyLength, true); RandomnessProvider.GetBytes(Entropy); var ciphertextBytes = ProtectedData.Protect(new Byte[length], Entropy, Scope); Ciphertext = new PinnedBuffer(ciphertextBytes.Length, true); Array.Copy(ciphertextBytes, Ciphertext, Ciphertext.Length); }
static void Main(String[] args) { Console.WriteLine("ZMQ version = {0}", Utils.GetZmqVersion()); var ctx = ZeroMQ.zmq_ctx_new(); if (ctx != null) { var subSocket = ZeroMQ.zmq_socket(ctx, ZeroMQ.ZMQ_SUB); if (subSocket != null) { if (0 == ZeroMQ.zmq_connect(subSocket, "tcp://localhost:60001")) { int numberOfSubscriptions = 0; for (int i = 0; i < args.Length; ++i) { using (var filter = PinnedBuffer.ASCII(args[i])) { if (-1 != ZeroMQ.zmq_setsockopt_2(subSocket, ZeroMQ.ZMQ_SUBSCRIBE, filter.Pointer, filter.Length)) { ++numberOfSubscriptions; } else { Console.WriteLine("subscription failed"); break; } } } if (numberOfSubscriptions > 0 && numberOfSubscriptions == args.Length) { Console.WriteLine("Listening..."); Console.WriteLine("[CTRL + C] to finish...\n"); ListenLoop(subSocket, Subscriptions()); } } else { Console.WriteLine("connection failed"); } ZeroMQ.zmq_close(subSocket); } else { Console.WriteLine("socket failed"); } ZeroMQ.zmq_ctx_term(ctx); } else { Console.WriteLine("context failed"); } }
public void ConstructWithExistingArray(int count) { Foo[] array = new Foo[count]; using (PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(array)) { Assert.False(buffer.IsDisposedOrLostArrayOwnership); Assert.Equal(array, buffer.Array); Assert.Equal(count, buffer.Count); VerifyPointer(buffer); } }
public void CastToSpan(int bufferLength) { using (PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(bufferLength)) { BufferSpan <Foo> span = buffer; Assert.Equal(buffer.Array, span.Array); Assert.Equal(0, span.Start); Assert.Equal(buffer.Pointer, span.PointerAtOffset); Assert.Equal(span.Length, bufferLength); } }
public void Span() { using (PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(42)) { BufferSpan <Foo> span = buffer.Span; Assert.Equal(buffer.Array, span.Array); Assert.Equal(0, span.Start); Assert.Equal(buffer.Pointer, span.PointerAtOffset); Assert.Equal(span.Length, 42); } }
public void WithStartAndLength(int bufferLength, int start, int spanLength) { using (PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(bufferLength)) { BufferSpan <Foo> span = buffer.Slice(start, spanLength); Assert.Equal(buffer.Array, span.Array); Assert.Equal(start, span.Start); Assert.Equal(buffer.Pointer + start * Unsafe.SizeOf <Foo>(), span.PointerAtOffset); Assert.Equal(span.Length, spanLength); } }
public void UnPinAndTakeArrayOwnership() { Foo[] data = null; using (PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(42)) { data = buffer.UnPinAndTakeArrayOwnership(); Assert.True(buffer.IsDisposedOrLostArrayOwnership); } Assert.NotNull(data); Assert.True(data.Length >= 42); }
public void ConstructWithOwnArray(int count) { using (PinnedBuffer <Foo> buffer = new PinnedBuffer <Foo>(count)) { Assert.False(buffer.IsDisposedOrLostArrayOwnership); Assert.NotNull(buffer.Array); Assert.Equal(count, buffer.Count); Assert.True(buffer.Array.Length >= count); VerifyPointer(buffer); } }
private T Decrypt(Byte[] ciphertext, PinnedBuffer key, SymmetricAlgorithmSpecification algorithm) { using (var cipher = algorithm.ToCipher(RandomnessProvider)) { using (var pinnedCiphertext = new PinnedBuffer(ciphertext, false)) { using (var plaintext = cipher.Decrypt(pinnedCiphertext, key)) { return(BinarySerializer.Deserialize(plaintext)); } } } }