static void Main(string[] args) { Mat m = Mat.Eye(new Size(2, 2), MatType.CV_32FC3); for (int y = 0; y < m.Rows; y++) { for (int x = 0; x < m.Cols; x++) { int offset = (int)m.Step() * y + m.ElemSize() * x; // offset 지정 Vec3b i = MarshalHelper.PtrToStructure <Vec3b>(m.Ptr(0) + offset + 0); Console.WriteLine($"{offset} - ({y}, {x}) : {i.Item0}, {i.Item1}, {i.Item2}"); } } }
public static int DeriveFromKey(byte[] subkey, ulong subkey_len, ulong subkey_id, sbyte[] ctx, byte[] key) { if (ctx == null || ctx.Length != 8) { throw new ArgumentOutOfRangeException("ctx", "The dimensions of the provided array don't match the required size."); } if (key == null || key.Length != 32) { throw new ArgumentOutOfRangeException("key", "The dimensions of the provided array don't match the required size."); } var __ret = __Internal.DeriveFromKey(MarshalHelper.ByteArrayToIntPtr(subkey), subkey_len, subkey_id, ctx, key); return(__ret); }
public MethodProcessor(TypeProcessor typeContext, MethodDefinition method) { TypeContext = typeContext; Method = method; MarshalProcessors = new MarshalProcessor[Method.Parameters.Count]; for (int i = 0; i < Method.Parameters.Count; i++) { var p = Method.Parameters[i]; MarshalProcessors[i] = MarshalHelper.GetMarshaler(this, p); } ReturnParameterMarshaler = MarshalHelper.GetMarshaler(this, Method.MethodReturnType); }
/// <summary> /// Retrieves the text in the window's title bar. /// </summary> public string GetTitle() { int length = User32.GetWindowTextLength(Handle); var buffer = new StringBuilder(length + 1); if (User32.GetWindowText(Handle, buffer, buffer.Capacity) == 0) { // The window might as well have no title/empty title, // but no exception will be thrown in that scenario since no error code is set. MarshalHelper.ThrowLastWin32ErrorException(); } return(buffer.ToString()); }
/// <summary> /// Converts std::vector to managed array /// </summary> /// <returns></returns> public KeyPoint[] ToArray() { int size = Size; if (size == 0) { return(new KeyPoint[0]); } KeyPoint[] dst = new KeyPoint[size]; using (var dstPtr = new ArrayAddress1 <KeyPoint>(dst)) { MemoryHelper.CopyMemory(dstPtr, ElemPtr, MarshalHelper.SizeOf <KeyPoint>() * dst.Length); } return(dst); }
/// <summary> /// Converts std::vector to managed array /// </summary> /// <returns></returns> public DMatch[] ToArray() { int size = Size; if (size == 0) { return(new DMatch[0]); } DMatch[] dst = new DMatch[size]; using (var dstPtr = new ArrayAddress1 <DMatch>(dst)) { MemoryHelper.CopyMemory(dstPtr, ElemPtr, MarshalHelper.SizeOf <DMatch>() * dst.Length); } return(dst); }
/// <summary> /// Initializes buffer with data /// </summary> public void SetBuffer(int index, int type, byte[] buffer) { // check object state if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } // parameters validation if ((index < 0) || (index >= BuffersCount)) { throw new ArgumentOutOfRangeException("index"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (buffer.Length == 0) { throw new ArgumentOutOfRangeException("buffer.Length"); } // allocate buffer int size = buffer.Length; IntPtr bufferData = Win32.LocalAlloc(Win32.LMEM_ZEROINIT, (uint)size); if (bufferData == IntPtr.Zero) { throw new OutOfMemoryException(); } try { // copy buffer data Marshal.Copy(buffer, 0, bufferData, size); // create buffer descriptor IntPtr secBuffer = IntPtrHelper.Add(pvBuffers, index * SSPINative.SecBuffer.Size); MarshalHelper.WriteInt32(secBuffer, typeof(SSPINative.SecBuffer), "BufferSize", size); MarshalHelper.WriteInt32(secBuffer, typeof(SSPINative.SecBuffer), "BufferType", type); MarshalHelper.WriteIntPtr(secBuffer, typeof(SSPINative.SecBuffer), "pvBuffer", bufferData); } catch { Win32.LocalFree(bufferData); throw; } }
/// <summary> /// Converts std::vector to managed array /// </summary> /// <returns></returns> public DTrees.Split[] ToArray() { int size = Size; if (size == 0) { return(new DTrees.Split[0]); } var dst = new DTrees.Split[size]; using (var dstPtr = new ArrayAddress1 <DTrees.Split>(dst)) { MemoryHelper.CopyMemory(dstPtr, ElemPtr, MarshalHelper.SizeOf <DTrees.Split>() * dst.Length); } return(dst); }
/// <summary> /// Invoke DeviceIOControl with no input, and retrieve the output in the form of an object of type T. /// </summary> public static T InvokeIoControl <T>(SafeFileHandle handle, IOControlCode controlCode) { uint returnedBytes = 0; object output = default(T); uint outputSize = MarshalHelper.SizeOf <T>(); bool success = DeviceIoControl(handle, controlCode, null, 0, output, outputSize, ref returnedBytes, IntPtr.Zero); if (!success) { int lastError = Marshal.GetLastWin32Error(); throw new Win32Exception("Couldn't invoke DeviceIoControl for " + controlCode + ". LastError: " + Utils.GetWin32ErrorMessage(lastError)); } return((T)output); }
public static int EncryptDetachedAfternm(byte[] c, byte[] mac, ref ulong maclen_p, byte[] m, ulong mlen, byte[] ad, ulong adlen, byte[] nsec, byte[] npub, byte[] ctx_) { fixed(ulong *__refParamPtr2 = &maclen_p) { var __arg2 = __refParamPtr2; if (ctx_ == null || ctx_.Length != 512) { throw new ArgumentOutOfRangeException("ctx_", "The dimensions of the provided array don't match the required size."); } var __ret = __Internal.EncryptDetachedAfternm(MarshalHelper.ByteArrayToIntPtr(c), MarshalHelper.ByteArrayToIntPtr(mac), __arg2, MarshalHelper.ByteArrayToIntPtr(m), mlen, MarshalHelper.ByteArrayToIntPtr(ad), adlen, MarshalHelper.ByteArrayToIntPtr(nsec), MarshalHelper.ByteArrayToIntPtr(npub), ctx_); return(__ret); } }
/// <summary> /// Repeatedly invokes InvokeIoControl with the specified input, as long as it gets return code 234 ("More data available") from the method. /// </summary> public static byte[] InvokeIoControlUnknownSize <V>(SafeFileHandle handle, IOControlCode controlCode, V input, uint increment = 128, uint inputSizeOverride = 0) { uint returnedBytes = 0; uint inputSize; uint outputLength = increment; if (inputSizeOverride > 0) { inputSize = inputSizeOverride; } else { inputSize = MarshalHelper.SizeOf <V>(); } do { byte[] output = new byte[outputLength]; bool success = DeviceIoControl(handle, controlCode, input, inputSize, output, outputLength, ref returnedBytes, IntPtr.Zero); if (!success) { int lastError = Marshal.GetLastWin32Error(); if (lastError == 234) { // More data outputLength += increment; continue; } throw new Win32Exception("Couldn't invoke DeviceIoControl for " + controlCode + ". LastError: " + Utils.GetWin32ErrorMessage(lastError)); } // Return the result if (output.Length == returnedBytes) { return(output); } byte[] res = new byte[returnedBytes]; Array.Copy(output, res, (int)returnedBytes); return(res); } while (true); }
internal void FreeBuffers() { IntPtr secBuffer = pvBuffers; for (int i = 0; i < BuffersCount; ++i) { IntPtr bufferData = MarshalHelper.ReadIntPtr(secBuffer, typeof(SSPINative.SecBuffer), "pvBuffer"); if (bufferData != IntPtr.Zero) { Win32.LocalFree(bufferData); } secBuffer = IntPtrHelper.Add(pvBuffers, SSPINative.SecBuffer.Size); } Win32.RtlZeroMemory(pvBuffers, (uint)(SSPINative.SecBuffer.Size * BuffersCount)); }
/// <summary> /// Calls InvokeIoControl with the specified input, returning a byte array. It allows the caller to handle errors. /// </summary> public static byte[] InvokeIoControl <V>(SafeFileHandle handle, IOControlCode controlCode, uint outputLength, V input, out int errorCode) { uint returnedBytes = 0; uint inputSize = MarshalHelper.SizeOf <V>(); errorCode = 0; byte[] output = new byte[outputLength]; bool success = DeviceIoControl(handle, controlCode, input, inputSize, output, outputLength, ref returnedBytes, IntPtr.Zero); if (!success) { errorCode = Marshal.GetLastWin32Error(); } return(output); }
/// <summary> /// Converts std::vector to managed array /// </summary> /// <returns></returns> public DMatch[] ToArray() { int size = Size; if (size == 0) { return(new DMatch[0]); } DMatch[] dst = new DMatch[size]; using (var dstPtr = new ArrayAddress1 <DMatch>(dst)) { MemoryHelper.CopyMemory(dstPtr, ElemPtr, MarshalHelper.SizeOf <DMatch>() * dst.Length); } GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so // make sure we are not disposed until finished with copy. return(dst); }
internal AccessControlEntry(IntPtr pAce) { // parameters validation if (pAce == IntPtr.Zero) { throw new ArgumentNullException("pAce"); } // read ACE properties _aceType = (AccessControlEntryType)MarshalHelper.ReadByte(pAce, typeof(SecurityNative.ACE), "AceType"); _aceFlags = (AccessControlEntryFlags)MarshalHelper.ReadByte(pAce, typeof(SecurityNative.ACE), "AceFlags"); _accessMask = (AccessMask)MarshalHelper.ReadInt32(pAce, typeof(SecurityNative.ACE), "AccessMask"); // read SID IntPtr pSid = IntPtrHelper.Add(pAce, Marshal.OffsetOf(typeof(SecurityNative.ACE), "SidStart")); Trustee = new SecurityIdentifier(pSid, true); }
/// <summary> /// Converts std::vector to managed array /// </summary> /// <returns></returns> public KeyPoint[] ToArray() { var size = Size; if (size == 0) { return(Array.Empty <KeyPoint>()); } var dst = new KeyPoint[size]; using (var dstPtr = new ArrayAddress1 <KeyPoint>(dst)) { MemoryHelper.CopyMemory(dstPtr.Pointer, ElemPtr, MarshalHelper.SizeOf <KeyPoint>() * dst.Length); } GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so // make sure we are not disposed until finished with copy. return(dst); }
/// <summary> /// Enumerates all top-level windows on the screen. /// </summary> public static List <WindowInfo> GetWindows() { var windows = new List <WindowInfo>(); bool success = User32.EnumWindows( (handle, lparam) => { windows.Add(new WindowInfo(handle)); return(true); }, IntPtr.Zero); if (!success) { MarshalHelper.ThrowLastWin32ErrorException(); } return(windows); }
/// <summary> /// Changes the query parameters associated with the <see cref="QueryCondition" />. /// </summary> /// <param name="queryParameters">The query parameters values to be set.</param> /// <returns>The <see cref="ReturnCode" /> that indicates the operation result.</returns> public ReturnCode SetQueryParameters(params string[] queryParameters) { if (queryParameters == null) { return(ReturnCode.BadParameter); } IntPtr seq = IntPtr.Zero; MarshalHelper.StringSequenceToPtr(queryParameters, ref seq, false); if (seq.Equals(IntPtr.Zero)) { return(ReturnCode.Error); } ReturnCode ret = UnsafeNativeMethods.SetQueryParameters(_native, seq); return(ret); }
/// <summary> /// Gets the query parameters associated with the <see cref="QueryCondition" />. That is, the parameters specified on the last /// successful call to <see cref="SetQueryParameters" />, or if <see cref="SetQueryParameters" /> was never called, the arguments specified when the /// <see cref="QueryCondition" /> was created. /// </summary> /// <param name="queryParameters">The query parameters list to be filled up.</param> /// <returns>The <see cref="ReturnCode" /> that indicates the operation result.</returns> public ReturnCode GetQueryParameters(IList <string> queryParameters) { if (queryParameters == null) { return(ReturnCode.BadParameter); } queryParameters.Clear(); IntPtr seq = IntPtr.Zero; ReturnCode ret = UnsafeNativeMethods.GetQueryParameters(_native, ref seq); if (ret == ReturnCode.Ok && !seq.Equals(IntPtr.Zero)) { MarshalHelper.PtrToStringSequence(seq, ref queryParameters, false); } return(ret); }
private SafeCoTaskMemHandle CreateHeifReader() { // This must be allocated in unmanaged memory because LibHeif keeps a reference // to this structure. var readerHandle = SafeCoTaskMemHandle.Allocate(MarshalHelper.SizeOf <heif_reader>()); unsafe { var reader = (heif_reader *)readerHandle.DangerousGetHandle(); reader->reader_api_version = 1; reader->get_position = Marshal.GetFunctionPointerForDelegate(this.getPositionDelegate); reader->read = Marshal.GetFunctionPointerForDelegate(this.readDelegate); reader->seek = Marshal.GetFunctionPointerForDelegate(this.seekDelegate); reader->wait_for_file_size = Marshal.GetFunctionPointerForDelegate(this.waitForFileSizeDelegate); } return(readerHandle); }
public static byte[] Get(global::Leveldb.DB db, global::Leveldb.Readoptions options, string key, ulong keylen, ref ulong vallen, sbyte[] errptr) { try { var __arg0 = ReferenceEquals(db, null) ? global::System.IntPtr.Zero : db.__Instance; var __arg1 = ReferenceEquals(options, null) ? global::System.IntPtr.Zero : options.__Instance; fixed(ulong *__refParamPtr4 = &vallen) { var __arg4 = __refParamPtr4; var __ret = __Internal.Get(__arg0, __arg1, key, keylen, __arg4, MarshalHelper.SByteArrayToSbytePtrArray(errptr)); return(MarshalHelper.IntPtrToByteArray((IntPtr)__ret, (int)vallen)); } } catch { return(null); } }
/// <summary> /// 站点配置更新 /// </summary> public static byte[] UpdateChannelInfo(ChannelStruct channelStruct) { /********************************************下载测点结构:******************************************* * 【 1 | $】 * 【 2 | P(point)】 * 【 3~264| struct ChannelInfo 】 262字节 * 【265校验 】 **************************************************************************************************************/ channelStruct.AreaName = new char[30]; channelStruct.MachineName = new char[30]; channelStruct.MonitorIDName = new char[30]; byte[] structData = MarshalHelper.StructToBytes(channelStruct, 266); byte[] cmd = new byte[266 + 3]; cmd[0] = (byte)'$'; cmd[1] = (byte)'P'; Array.Copy(structData, 0, cmd, 2, 266); cmd[268] = (byte)'$'; return(cmd); }
/// <summary> /// Retrieves the process that created the window, when available. /// </summary> /// <returns>The process when available, null otherwise.</returns> public Process GetProcess() { if (_process == null) { uint processId; uint threadId = User32.GetWindowThreadProcessId(Handle, out processId); if (threadId == 0) { MarshalHelper.ThrowLastWin32ErrorException(); } try { _process = processId == 0 ? null : Process.GetProcessById((int)processId); } catch (ArgumentException) { // The process specified by processId parameter is not running. // GetWindowThreadProcessId at one point returned a processId of a process which was not running. Possibly a remnant window of a crashed process? _process = null; } if (_process != null) { try { _processThread = ( from ProcessThread t in _process.Threads where t.Id == threadId select t).First(); } catch (InvalidOperationException) { // Process has since been shut down. _process = null; } } } return(_process); }
/// <summary><see cref="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365171(v=vs.85).aspx"/></summary> public DISK_GEOMETRY_EX DiskGetDriveGeometryEx() { byte[] data = DeviceIoControlHelper.InvokeIoControlUnknownSize(Handle, IOControlCode.DiskGetDriveGeometryEx, 256); DISK_GEOMETRY_EX res; using (UnmanagedMemory mem = new UnmanagedMemory(data)) { res.Geometry = mem.Handle.ToStructure <DISK_GEOMETRY>(); res.DiskSize = BitConverter.ToInt64(data, (int)MarshalHelper.SizeOf <DISK_GEOMETRY>()); IntPtr tmpPtr = new IntPtr(mem.Handle.ToInt64() + MarshalHelper.SizeOf <DISK_GEOMETRY>() + sizeof(long)); res.PartitionInformation = tmpPtr.ToStructure <DISK_PARTITION_INFO>(); tmpPtr = new IntPtr(tmpPtr.ToInt64() + res.PartitionInformation.SizeOfPartitionInfo); res.DiskInt13Info = tmpPtr.ToStructure <DISK_EX_INT13_INFO>(); } return(res); }
public static global::Leveldb.DB Open(global::Leveldb.Options options, string name, sbyte[] errptr) { var __arg0 = ReferenceEquals(options, null) ? global::System.IntPtr.Zero : options.__Instance; var __ret = __Internal.Open(__arg0, name, MarshalHelper.SByteArrayToSbytePtrArray(errptr)); global::Leveldb.DB __result0; if (__ret == IntPtr.Zero) { __result0 = null; } else if (global::Leveldb.DB.NativeToManagedMap.ContainsKey(__ret)) { __result0 = (global::Leveldb.DB)global::Leveldb.DB.NativeToManagedMap[__ret]; } else { __result0 = global::Leveldb.DB.__CreateInstance(__ret); } return(__result0); }
private SafeCoTaskMemHandle CreateHeifWriter() { if (!this.stream.CanWrite) { throw new IOException(Resources.StreamCannotWrite); } this.writerErrors = new WriterErrors(); var writerHandle = SafeCoTaskMemHandle.Allocate(MarshalHelper.SizeOf <heif_writer>()); unsafe { var writer = (heif_writer *)writerHandle.DangerousGetHandle(); writer->heif_writer_version = 1; writer->write = Marshal.GetFunctionPointerForDelegate(this.writeDelegate); } return(writerHandle); }
/// <summary> /// Gets the collection of subscriptions currently "associated" with the <see cref="DataWriter" />; that is, subscriptions that have a /// matching <see cref="Topic" /> and compatible QoS that the application has not indicated should be "ignored" by means of the /// <see cref="DomainParticipant" /> IgnoreSubscription operation. /// </summary> /// <remarks> /// The handles returned in the 'subscriptionHandles' collection are the ones that are used by the DDS implementation to locally /// identify the corresponding matched <see cref="DataReader" /> entities. These handles match the ones that appear in the <see cref="SampleInfo.InstanceState" /> /// property of the <see cref="SampleInfo" /> when reading the "DCPSSubscriptions" builtin topic. /// </remarks> /// <param name="subscriptionHandles">The collection of subscription <see cref="InstanceHandle" />s to be filled up.</param> /// <returns>The <see cref="ReturnCode" /> that indicates the operation result.</returns> public ReturnCode GetMatchedSubscriptions(ICollection <InstanceHandle> subscriptionHandles) { if (subscriptionHandles == null) { return(ReturnCode.BadParameter); } subscriptionHandles.Clear(); IntPtr seq = IntPtr.Zero; ReturnCode ret = UnsafeNativeMethods.GetMatchedSubscriptions64(_native, ref seq); if (ret == ReturnCode.Ok && !seq.Equals(IntPtr.Zero)) { MarshalHelper.PtrToSequence(seq, ref subscriptionHandles); MarshalHelper.ReleaseNativePointer(seq); } return(ret); }
private static unsafe string? HandleNfdResult(sw_nfdresult result, byte* outPath) { switch (result) { case sw_nfdresult.SW_NFD_ERROR: var errPtr = sw_NFD_GetError(); throw new Exception(MarshalHelper.PtrToStringUTF8(errPtr)); case sw_nfdresult.SW_NFD_OKAY: var str = MarshalHelper.PtrToStringUTF8(outPath)!; sw_NFD_Free(outPath); return str; case sw_nfdresult.SW_NFD_CANCEL: return null; default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// Write a specified structure to the allocated memory. /// </summary> /// <typeparam name="T">The structure type to write to memory.</typeparam> /// <param name="structure"></param> public void Write <T>(T structure) where T : struct { uint bytesToWrite = (uint)Marshal.SizeOf(typeof(T)); T[] buffer = { structure }; GCHandle pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); UIntPtr bytesRead; bool success = Kernel32.WriteProcessMemory( _processHandle, Address, Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0), new UIntPtr(bytesToWrite), out bytesRead); pinnedBuffer.Free(); if (!success) { MarshalHelper.ThrowLastWin32ErrorException(); } }
private List <FilterModuleDescription> GetSubFilter(ModuleDescriptionStructure module) { var result = new List <FilterModuleDescription>(); var filterModule = FilterModuleDescription.GetFilterModuleDescription(module); if (filterModule == null) { return(result); } result.Add(filterModule); if (module.NextModule != IntPtr.Zero) { ModuleDescriptionStructure nextModule = MarshalHelper.PtrToStructure <ModuleDescriptionStructure>(module.NextModule); var data = GetSubFilter(nextModule); if (data.Count > 0) { result.AddRange(data); } } return(result); }