ToInt64() private method

private ToInt64 ( ) : long
return long
コード例 #1
0
        /// <summary>
        /// Converts Timespec to DateTime.
        /// Timespec needs to be of type GPRClockType.Realtime and needs to represent a legal value.
        /// DateTime has lower resolution (100ns), so rounding can occurs.
        /// Value are always rounded up to the nearest DateTime value in the future.
        ///
        /// For Timespec.InfFuture or if timespec is after the largest representable DateTime, DateTime.MaxValue is returned.
        /// For Timespec.InfPast or if timespec is before the lowest representable DateTime, DateTime.MinValue is returned.
        ///
        /// Unless DateTime.MaxValue or DateTime.MinValue is returned, the resulting DateTime is always in UTC
        /// (DateTimeKind.Utc)
        /// </summary>
        public DateTime ToDateTime()
        {
            Preconditions.CheckState(tv_nsec >= 0 && tv_nsec < NanosPerSecond);
            Preconditions.CheckState(clock_type == GPRClockType.Realtime);

            // fast path for InfFuture
            if (this.Equals(InfFuture))
            {
                return(DateTime.MaxValue);
            }

            // fast path for InfPast
            if (this.Equals(InfPast))
            {
                return(DateTime.MinValue);
            }

            try
            {
                // convert nanos to ticks, round up to the nearest tick
                long ticksFromNanos = tv_nsec / NanosPerTick + ((tv_nsec % NanosPerTick != 0) ? 1 : 0);
                long ticksTotal     = checked (tv_sec.ToInt64() * TicksPerSecond + ticksFromNanos);
                return(UnixEpoch.AddTicks(ticksTotal));
            }
            catch (OverflowException)
            {
                // ticks out of long range
                return(tv_sec.ToInt64() > 0 ? DateTime.MaxValue : DateTime.MinValue);
            }
            catch (ArgumentOutOfRangeException)
            {
                // resulting date time would be larger than MaxValue
                return(tv_sec.ToInt64() > 0 ? DateTime.MaxValue : DateTime.MinValue);
            }
        }
コード例 #2
0
 private byte* Align(IntPtr buf, uint alignTo)
 {
     //This makes an aligned buffer linux needs this.
     //The buffer must originally be at least one alignment bigger!
     var diff = alignTo - (buf.ToInt64() % alignTo);
     var aligned = (IntPtr)(buf.ToInt64() + diff);
     return (byte*)aligned;
 }
コード例 #3
0
ファイル: DllLoader.cs プロジェクト: azmodii/wkHtmlToPdfSharp
        } // End Function LoadSharedObject

        // wkHtmlToPdfSharp.NotwkHtmlToPdfSharp.OS.SharedLibrary.Unload(library);
        public static bool Unload(System.IntPtr hSO)
        {
            bool bError = true;

            if (hSO == IntPtr.Zero)
            {
                throw new ArgumentNullException("hSO");
            } // End if (hSO == IntPtr.Zero)

            try
            {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    // If the referenced object was successfully closed, dlclose() shall return 0.
                    // If the object could not be closed, or if handle does not refer to an open object,
                    // dlclose() shall return a non-zero value.
                    // More detailed diagnostic information shall be available through dlerror().

                    // http://stackoverflow.com/questions/956640/linux-c-error-undefined-reference-to-dlopen
                    if (dlclose(hSO) == 0)
                    {
                        bError = false;
                    }

                    if (bError)
                    {
                        throw new ApplicationException("Error unloading handle " + hSO.ToInt64().ToString() + Environment.NewLine + "System error message: " + dlerror());
                    }
                }
                else
                {
                    // FreeLibrary: If the function succeeds, the return value is nonzero.
                    // If the function fails, the return value is zero.
                    // To get extended error information, call the GetLastError function.
                    bError = !FreeLibrary(hSO);

                    if (bError)
                    {
                        throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                    }
                } // End if (Environment.OSVersion.Platform == PlatformID.Unix)
            }     // End Try
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            } // End Catch

            if (bError)
            {
                throw new ApplicationException("Cannot unload handle " + hSO.ToInt64().ToString());
            } // End if (hExe == IntPtr.Zero)

            return(bError);
        } // End Function Unload
コード例 #4
0
ファイル: Program.cs プロジェクト: toydev/ExampleCSharp
 static IntPtr GetReadSize(IntPtr pointer, IntPtr endPointer, int bufferSize)
 {
     if (endPointer.ToInt64() < IntPtr.Add(pointer, bufferSize).ToInt64())
     {
         return (IntPtr)(endPointer.ToInt64() - pointer.ToInt64());
     }
     else
     {
         return new IntPtr(bufferSize);
     }
 }
コード例 #5
0
        /// <summary>
        /// Read a hardware independent dictionary of language and code page identifier tables.
        /// </summary>
        /// <param name="lpRes">Pointer to the beginning of data.</param>
        /// <returns>Pointer to the end of data.</returns>
        internal override IntPtr Read(IntPtr lpRes)
        {
            _vars.Clear();
            IntPtr pChild = base.Read(lpRes);

            while (pChild.ToInt64() < (lpRes.ToInt64() + _header.wLength))
            {
                VarTable res = new VarTable(pChild);
                _vars.Add(res.Key, res);
                pChild = ResourceUtil.Align(pChild.ToInt64() + res.Header.wLength);
            }

            return new IntPtr(lpRes.ToInt64() + _header.wLength);
        }
コード例 #6
0
        /// <summary>
        /// Read a table of language and code page identifier pairs.
        /// </summary>
        /// <param name="lpRes">Pointer to the beginning of the data.</param>
        /// <returns></returns>
        internal override IntPtr Read(IntPtr lpRes)
        {
            _languages.Clear();
            IntPtr pVar = base.Read(lpRes);

            while (pVar.ToInt64() < (lpRes.ToInt64() + _header.wLength))
            {
                Kernel32.VAR_HEADER var = (Kernel32.VAR_HEADER) Marshal.PtrToStructure(
                    pVar, typeof(Kernel32.VAR_HEADER));
                _languages.Add(var.wLanguageIDMS, var.wCodePageIBM);
                pVar = new IntPtr(pVar.ToInt64() + Marshal.SizeOf(var));
            }

            return new IntPtr(lpRes.ToInt64() + _header.wLength);
        }
コード例 #7
0
ファイル: PyCall.cs プロジェクト: Pgde/EBot-master
 public static PyType? GetEveObjectType(IntPtr intptr, bool isDerived = false)
 {
     PyType? returnType;
     if (!_pythontypesLoaded)
     {
         PopulatePythonTypes();
     }
     if (intptr == IntPtr.Zero)
     {
         return PyType.Invalid;
     }
     IntPtr key = Marshal.ReadIntPtr(((IntPtr)intptr.ToInt64() + 4)); // Points to the type
     if (!_pythonTypes.TryGetValue(key, out returnType) && !isDerived)
     {
         returnType = GetEveObjectType(key, true);
         _pythonTypes.Add(key, returnType);
         return returnType;
     }
     if (isDerived)
     {
         string str = returnType.ToString();
         returnType = (PyType)Enum.Parse(typeof(PyType), "Derived" + str);
     }
     return returnType;
 }
コード例 #8
0
		static void Initialize (IntPtr ptr, IntPtr data)
		{
			IntPtr ifaceptr = new IntPtr (ptr.ToInt64 () + class_offset);
			AtkHyperlinkImplIface native_iface = (AtkHyperlinkImplIface) Marshal.PtrToStructure (ifaceptr, typeof (AtkHyperlinkImplIface));
			native_iface.GetHyperlink = iface.GetHyperlink;
			Marshal.StructureToPtr (native_iface, ifaceptr, false);
		}
コード例 #9
0
ファイル: Event.cs プロジェクト: theojulienne/Claro
 internal IntPtr make_offset(IntPtr base_ptr, int offset)
 {
     if(IntPtr.Size == 8)
         return new IntPtr( (long)offset + base_ptr.ToInt64() );
     else
         return new IntPtr( offset + base_ptr.ToInt32() );
 }
コード例 #10
0
 /// <summary>
 ///     Assemble the specified assembly code at a base address.
 /// </summary>
 /// <param name="asm">The assembly code.</param>
 /// <param name="baseAddress">The address where the code is rebased.</param>
 /// <returns>An array of bytes containing the assembly code.</returns>
 public byte[] Assemble(string asm, IntPtr baseAddress)
 {
     // Rebase the code
     asm = String.Format("use32\norg 0x{0:X8}\n", baseAddress.ToInt64()) + asm;
     // Assemble and return the code
     return FasmNet.Assemble(asm);
 }
コード例 #11
0
        /// <summary>
        ///     Constructor for WLAN_INTERFACE_INFO_LIST.
        ///     Constructor is needed because the InterfaceInfo member varies based on how many adapters are in the system.
        /// </summary>
        /// <param name="pointerToWlanInterfaceInfoList">the unmanaged pointer containing the list.</param>
        public WLAN_INTERFACE_INFO_LIST(IntPtr pointerToWlanInterfaceInfoList)
        {
            // The first 4 bytes are the number of WLAN_INTERFACE_INFO structures.
            this.dwNumberOfItems = Marshal.ReadInt32(pointerToWlanInterfaceInfoList, (0 * Marshal.SizeOf(typeof(int))));

            // The next 4 bytes are the index of the current item in the unmanaged API.
            this.dwIndex = Marshal.ReadInt32(pointerToWlanInterfaceInfoList, (1 * Marshal.SizeOf(typeof(int))));

            // Construct the array of WLAN_INTERFACE_INFO structures.
            this.InterfaceInfo = new WLAN_INTERFACE_INFO[this.dwNumberOfItems];

            // start pointer
            long start = pointerToWlanInterfaceInfoList.ToInt64() + (2 * Marshal.SizeOf(typeof(int))); // we skip 8 for the first and second int in the structure

            // get the size of WLAN_INTERFACE_INFO
            int sizeOfWlanInterfaceInfo = Marshal.SizeOf(typeof (WLAN_INTERFACE_INFO));

            // we know there are dwNumberOfItems in the struct
            // so we can take each of those memory pieces and marshal them to WLAN_INTERFACE_INFO

            for (int i = 0; i <= this.dwNumberOfItems - 1; i++)
            {
                var pItemList = new IntPtr(start + (i * sizeOfWlanInterfaceInfo));

                this.InterfaceInfo[i] = (WLAN_INTERFACE_INFO) Marshal.PtrToStructure(pItemList, typeof (WLAN_INTERFACE_INFO));
            }
        }
コード例 #12
0
		static void Initialize (IntPtr ptr, IntPtr data)
		{
			IntPtr ifaceptr = new IntPtr (ptr.ToInt64 () + class_offset);
			GFileDescriptorBasedIface native_iface = (GFileDescriptorBasedIface) Marshal.PtrToStructure (ifaceptr, typeof (GFileDescriptorBasedIface));
			native_iface.GetFd = iface.GetFd;
			Marshal.StructureToPtr (native_iface, ifaceptr, false);
		}
コード例 #13
0
ファイル: KeyEventArgsExt.cs プロジェクト: gdlprj/duscusys
        /// <summary>
        /// Creates <see cref="KeyEventArgsExt"/> from Windows Message parameters, based upon
        /// a local application hook.
        /// </summary>
        /// <param name="wParam">The first Windows Message parameter.</param>
        /// <param name="lParam">The second Windows Message parameter.</param>
        /// <returns>A new KeyEventArgsExt object.</returns>
        private static KeyEventArgsExt FromRawDataApp(int wParam, IntPtr lParam)
        {
            //http://msdn.microsoft.com/en-us/library/ms644984(v=VS.85).aspx

            const uint maskKeydown = 0x40000000; // for bit 30
            const uint maskKeyup = 0x80000000; // for bit 31

            int timestamp = Environment.TickCount;

            uint flags = 0u;
#if IS_X64
            // both of these are ugly hacks. Is there a better way to convert a 64bit IntPtr to uint?

            // flags = uint.Parse(lParam.ToString());
            flags = Convert.ToUInt32(lParam.ToInt64());
#else
            flags = (uint)lParam;
#endif
            

            //bit 30 Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
            bool wasKeyDown = (flags & maskKeydown) > 0;
            //bit 31 Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
            bool isKeyReleased = (flags & maskKeyup) > 0;

            Keys keyData = (Keys)wParam;

            bool isKeyDown = !wasKeyDown && !isKeyReleased;
            bool isKeyUp = wasKeyDown && isKeyReleased;

            return new KeyEventArgsExt(keyData, timestamp, isKeyDown, isKeyUp);
        }
コード例 #14
0
        /// <summary>
        /// Read the accelerator.
        /// </summary>
        /// <param name="lpRes">Address in memory.</param>
        internal IntPtr Read(IntPtr lpRes)
        {
            _accel = (User32.ACCEL) Marshal.PtrToStructure(
                lpRes, typeof(User32.ACCEL));

            return new IntPtr(lpRes.ToInt64() + Marshal.SizeOf(_accel));
        }
コード例 #15
0
 public HotKeyEventArgs(IntPtr hotKeyParam, IntPtr wParam)
 {
     uint param = (uint)hotKeyParam.ToInt64();
     Key = (Keys)((param & 0xffff0000) >> 16);
     Modifiers = (KeyModifiers)(param & 0x0000ffff);
     this.ID = (int)wParam;
 }
コード例 #16
0
		internal static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
		{
			if (msg != CUSTOM_MESSAGE) {
				return IntPtr.Zero;
			}
			handled = true;
			long fileNumber = wParam.ToInt64();
			long openEvenIfProjectIsOpened = lParam.ToInt64();
			LoggingService.Info("Receiving custom message...");
			if (openEvenIfProjectIsOpened == 0 && ProjectService.OpenSolution != null) {
				return new IntPtr(RESULT_PROJECT_IS_OPEN);
			} else {
				try {
					SD.MainThread.InvokeAsyncAndForget(delegate {
						var win32Window = PresentationSource.FromVisual(SD.Workbench.MainWindow) as System.Windows.Interop.IWin32Window;
						if (win32Window != null) {
							NativeMethods.SetForegroundWindow(win32Window.Handle);
						}
					});
					string tempFileName = Path.Combine(Path.GetTempPath(), "sd" + fileNumber + ".tmp");
					foreach (string file in File.ReadAllLines(tempFileName)) {
						SD.MainThread.InvokeAsyncAndForget(delegate {
							SharpDevelop.FileService.OpenFile(file);
						});
					}
				} catch (Exception ex) {
					LoggingService.Warn(ex);
				}
				return new IntPtr(RESULT_FILES_HANDLED);
			}
		}
コード例 #17
0
        /// <summary>
        /// Primitive patching. Inserts a jump to 'target' at 'site'. Works even if both methods'
        /// callers have already been compiled.
        /// </summary>
        /// <param name="site"></param>
        /// <param name="target"></param>
        public static RedirectCallsState PatchJumpTo(IntPtr site, IntPtr target)
        {
            RedirectCallsState state = new RedirectCallsState();

            // R11 is volatile.
            unsafe
            {
                byte* sitePtr = (byte*)site.ToPointer();
                state.a = *sitePtr;
                state.b = *(sitePtr + 1);
                state.c = *(sitePtr + 10);
                state.d = *(sitePtr + 11);
                state.e = *(sitePtr + 12);
                state.f = *((ulong*) (sitePtr + 2));

                *sitePtr = 0x49; // mov r11, target
                *(sitePtr + 1) = 0xBB;
                *((ulong*)(sitePtr + 2)) = (ulong)target.ToInt64();
                *(sitePtr + 10) = 0x41; // jmp r11
                *(sitePtr + 11) = 0xFF;
                *(sitePtr + 12) = 0xE3;
            }

            return state;
        }
コード例 #18
0
ファイル: MyMapping.cs プロジェクト: viktorius/Viktor
 internal void WriteAndPositionByRow <T>(T[] data, int count, int offset = 0) where T : struct
 {
     Debug.Assert(count <= m_dataBox.RowPitch);
     Utilities.Write(m_dataPointer, data, offset, count);
     m_dataPointer += m_dataBox.RowPitch;
     Debug.Assert((m_dataPointer.ToInt64() - m_dataBox.DataPointer.ToInt64()) <= m_bufferSize);
 }
コード例 #19
0
        public static UInt32 NtWriteFile(
            IntPtr FileHandle,
            IntPtr Event,
            IntPtr ApcRoutine,
            IntPtr ApcContext,
            IntPtr IoStatusBlock,
            IntPtr Buffer,
            UInt32 Length,
            UInt32 ByteOffset,
            UInt32 Key)
        {
            if (DetourBlock.IsDetouring) {
                return OriginalFn(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
                    Buffer, Length, ByteOffset, Key);
            }

            using (var block = new DetourBlock())
            {
                var result = OriginalFn(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
                    Buffer, Length, ByteOffset, Key);

                if (result == 0 /* STATUS_SUCCESS */)
                {
                    Remoting.Scribe.DocumentFileWrite(Process.GetCurrentProcess().Id, FileHandle.ToInt64());
                }

                return result;
            }
        }
コード例 #20
0
 /// <summary>
 ///     Assemble the specified assembly code at a base address.
 /// </summary>
 /// <param name="asm">The assembly code.</param>
 /// <param name="baseAddress">The address where the code is rebased.</param>
 /// <returns>An array of bytes containing the assembly code.</returns>
 public byte[] Assemble(string asm, IntPtr baseAddress)
 {
     // Rebase the code
     asm = $"use32\norg 0x{baseAddress.ToInt64():X8}\n" + asm;
     // Assemble and return the code
     return FasmNet.Assemble(asm);
 }
コード例 #21
0
ファイル: UVStream.cs プロジェクト: GamingAtheist/LibuvSharp
 internal UVStream(Loop loop, IntPtr handle)
     : base(loop, handle)
 {
     read_cb_unix = read_callback_u;
     read_cb_win = read_callback_w;
     stream = (uv_stream_t *)(handle.ToInt64() + Handle.Size(HandleType.UV_HANDLE));
 }
コード例 #22
0
        private static void DeviceAdded(System.IntPtr context, System.IntPtr res, System.IntPtr sender, System.IntPtr device)
        {
            if (MacNative.IOHIDDeviceOpen(device, IntPtr.Zero) == IntPtr.Zero)
            {
                if (MacNative.IOHIDDeviceConformsTo(device, HIDDesktop, HIDJoystick) ||
                    MacNative.IOHIDDeviceConformsTo(device, HIDDesktop, HIDGamePad) ||
                    MacNative.IOHIDDeviceConformsTo(device, HIDDesktop, HIDMultiAxis) ||
                    MacNative.IOHIDDeviceConformsTo(device, HIDDesktop, HIDWheel))
                {
                    System.IntPtr product     = MacNative.IOHIDDeviceGetProperty(device, MacNative.CFString("Product"));
                    string        productName = MacNative.CString(product);

                    int index = 0;
                    foreach (Engine.Joystick joystick in engine.joysticks)
                    {
                        if (joystick == null)
                        {
                            engine.joysticks [index]       = new Engine.Joystick();
                            engine.joysticks [index].index = index;
                            engine.joysticks [index].id    = device.ToInt64();
                            engine.joysticks [index].name  = productName;
                            MacNative.IOHIDDeviceRegisterInputValueCallback(device, DeviceInputCallback, device);
                            MacNative.IOHIDDeviceScheduleWithRunLoop(device, runLoop, defaultLoopMode);
                            return;
                        }
                        index++;
                    }
                }
                MacNative.IOHIDDeviceClose(device, IntPtr.Zero);
            }
        }
コード例 #23
0
 private static byte[] IntPtrToBytes(IntPtr p, long offset, long length)
 {
     byte[] buffer = new byte[0x10 + IntPtr.Size];
     for (int i = 0; i < 8; i++)
     {
         buffer[i] = (byte) ((offset >> (8 * i)) & 0xffL);
     }
     for (int j = 0; j < 8; j++)
     {
         buffer[8 + j] = (byte) ((length >> (8 * j)) & 0xffL);
     }
     if (IntPtr.Size == 4)
     {
         int num3 = p.ToInt32();
         for (int m = 0; m < 4; m++)
         {
             buffer[0x10 + m] = (byte) ((num3 >> (8 * m)) & 0xff);
         }
         return buffer;
     }
     long num5 = p.ToInt64();
     for (int k = 0; k < 8; k++)
     {
         buffer[0x10 + k] = (byte) ((num5 >> (8 * k)) & 0xffL);
     }
     return buffer;
 }
コード例 #24
0
 /// <summary>
 /// Read the resource.
 /// </summary>
 /// <param name="hModule">Module handle.</param>
 /// <param name="lpRes">Pointer to the beginning of a resource.</param>
 /// <returns>Pointer to the end of the resource.</returns>
 internal override IntPtr Read(IntPtr hModule, IntPtr lpRes)
 {
     byte[] data = new byte[_size];
     Marshal.Copy(lpRes, data, 0, data.Length);
     _bitmap = new DeviceIndependentBitmap(data);
     return new IntPtr(lpRes.ToInt64() + _size);
 }
コード例 #25
0
ファイル: EoWrapper.cs プロジェクト: conr2d/efl
            /// <summary>Initializes a new instance of the <see cref="Object"/> class.
            /// Internal usage: Constructor to actually call the native library constructors. C# subclasses
            /// must use the public constructor only.</summary>
            /// <param name="baseKlass">The pointer to the base native Eo class.</param>
            /// <param name="managedType">The managed type of the public constructor that originated this call.</param>
            /// <param name="parent">The Efl.Object parent of this instance.</param>
            /// <param name="file">Name of the file from where the constructor is called.</param>
            /// <param name="line">Number of the line from where the constructor is called.</param>
            protected EoWrapper(IntPtr baseKlass, System.Type managedType, Efl.Object parent,
                                [CallerFilePath] string file = null,
                                [CallerLineNumber] int line  = 0)
            {
                inherited = ((object)this).GetType() != managedType;
                IntPtr actual_klass = baseKlass;

                if (inherited)
                {
                    actual_klass = Efl.Eo.ClassRegister.GetInheritKlassOrRegister(baseKlass, ((object)this).GetType());
                }

                // Creation of the unfinalized Eo handle
                Eina.Log.Debug($"Instantiating from klass 0x{actual_klass.ToInt64():x}");
                System.IntPtr parent_ptr = System.IntPtr.Zero;
                if (parent != null)
                {
                    parent_ptr = parent.NativeHandle;
                }

                handle = Efl.Eo.Globals._efl_add_internal_start(file, line, actual_klass, parent_ptr, 1, 0);
                if (handle == System.IntPtr.Zero)
                {
                    throw new Exception("Instantiation failed");
                }

                Eina.Log.Debug($"Eo instance right after internal_start 0x{handle.ToInt64():x} with refcount {Efl.Eo.Globals.efl_ref_count(handle)}");
                Eina.Log.Debug($"Parent was 0x{parent_ptr.ToInt64()}");

                // Creation of wrapper supervisor
                AddWrapperSupervisor();
            }
コード例 #26
0
        public static ItemPropertyValue[] ReadItemPropertyValues(int size, IntPtr dataPtr, IntPtr errorsPtr)
        {
            try
            {
                var results = new ItemPropertyValue[size];
                var dataPtrAsLong = dataPtr.ToInt64();
                for (var i = 0; i < size; i++)
                {
                    var valuePtr = new IntPtr(dataPtrAsLong + i * NativeMethods.VariantSize);
                    if (valuePtr != IntPtr.Zero)
                    {
                        results[i].Value = Marshal.GetObjectForNativeVariant(valuePtr);
                        NativeMethods.VariantClear(valuePtr);
                    }
                    results[i].Error = Marshal.ReadInt32(errorsPtr, i * sizeof(int));
                }

                return results;
            }
            finally
            {
                if (dataPtr != IntPtr.Zero)
                    Marshal.FreeCoTaskMem(dataPtr);
                if (errorsPtr != IntPtr.Zero)
                    Marshal.FreeCoTaskMem(errorsPtr);
            }            
        }
コード例 #27
0
		static void Initialize (IntPtr ptr, IntPtr data)
		{
			IntPtr ifaceptr = new IntPtr (ptr.ToInt64 () + class_offset);
			GtkCellEditableIface native_iface = (GtkCellEditableIface) Marshal.PtrToStructure (ifaceptr, typeof (GtkCellEditableIface));
			native_iface.StartEditing = iface.StartEditing;
			Marshal.StructureToPtr (native_iface, ifaceptr, false);
		}
コード例 #28
0
		static void Initialize (IntPtr ptr, IntPtr data)
		{
			IntPtr ifaceptr = new IntPtr (ptr.ToInt64 () + class_offset);
			GtkActivatableIface native_iface = (GtkActivatableIface) Marshal.PtrToStructure (ifaceptr, typeof (GtkActivatableIface));
			native_iface.SyncActionProperties = iface.SyncActionProperties;
			Marshal.StructureToPtr (native_iface, ifaceptr, false);
		}
コード例 #29
0
        private static void UpdateLeds(ICollection<KeyValuePair<int, CorsairLed>> ledsToUpdate)
        {
            ledsToUpdate = ledsToUpdate.Where(x => x.Value.Color != Color.Transparent).ToList();

            if (!ledsToUpdate.Any())
                return; // CUE seems to crash if 'CorsairSetLedsColors' is called with a zero length array

            int structSize = Marshal.SizeOf(typeof(_CorsairLedColor));
            IntPtr ptr = Marshal.AllocHGlobal(structSize * ledsToUpdate.Count);
            IntPtr addPtr = new IntPtr(ptr.ToInt64());
            foreach (KeyValuePair<int, CorsairLed> led in ledsToUpdate)
            {
                _CorsairLedColor color = new _CorsairLedColor
                {
                    ledId = led.Key,
                    r = led.Value.Color.R,
                    g = led.Value.Color.G,
                    b = led.Value.Color.B
                };

                Marshal.StructureToPtr(color, addPtr, false);
                addPtr = new IntPtr(addPtr.ToInt64() + structSize);
            }
            _CUESDK.CorsairSetLedsColors(ledsToUpdate.Count, ptr);
            Marshal.FreeHGlobal(ptr);
        }
コード例 #30
0
 /// <summary> Constructs a stream that marshals bytes from unmanaged memory </summary>
 public MarshallingStream(IntPtr ptrBytes, bool readOnly, int start, int length)
 {
     _ptrBytes = start == 0 ? ptrBytes : new IntPtr(ptrBytes.ToInt64() + start);
     _readOnly = readOnly;
     _length = length;
     _position = 0;
 }
コード例 #31
0
ファイル: SingleInstanceHelper.cs プロジェクト: Altaxo/Altaxo
		internal static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
		{
			if (msg != CUSTOM_MESSAGE) {
				return IntPtr.Zero;
			}
			handled = true;
			long fileNumber = wParam.ToInt64();
			long openEvenIfProjectIsOpened = lParam.ToInt64();
			LoggingService.Info("Receiving custom message...");
			if (openEvenIfProjectIsOpened == 0 && ProjectService.OpenSolution != null) {
				return new IntPtr(RESULT_PROJECT_IS_OPEN);
			} else {
				try {
					WorkbenchSingleton.SafeThreadAsyncCall(
						delegate { NativeMethods.SetForegroundWindow(WorkbenchSingleton.MainWin32Window.Handle) ; }
					);
					string tempFileName = Path.Combine(Path.GetTempPath(), "sd" + fileNumber + ".tmp");
					foreach (string file in File.ReadAllLines(tempFileName)) {
						WorkbenchSingleton.SafeThreadAsyncCall(
							delegate(string openFileName) { FileService.OpenFile(openFileName); }
							, file
						);
					}
				} catch (Exception ex) {
					LoggingService.Warn(ex);
				}
				return new IntPtr(RESULT_FILES_HANDLED);
			}
		}
コード例 #32
0
ファイル: BASS_PLUGININFO.cs プロジェクト: safawu/project2006
 private unsafe void ReadArrayStructure(int count, IntPtr p)
 {
     for (int i = 0; i < count; i++)
     {
         formats[i] = (BASS_PLUGINFORM) Marshal.PtrToStructure(p, typeof(BASS_PLUGINFORM));
         p = new IntPtr(p.ToInt64() + Marshal.SizeOf(formats[i]));
     }
 }
コード例 #33
0
        public static bool IsInvalidHandleValue(IntPtr p)
        {
            long h = p.ToInt64();
            if(h == -1) return true;
            if(h == 0xFFFFFFFF) return true;

            return false;
        }
コード例 #34
0
ファイル: TagSetterAdapter.cs プロジェクト: jwzl/ossbuild
		static void Initialize (IntPtr ptr, IntPtr data)
		{
			IntPtr ifaceptr = new IntPtr (ptr.ToInt64 () + class_offset);
			GstTagSetterIFace native_iface = (GstTagSetterIFace) Marshal.PtrToStructure (ifaceptr, typeof (GstTagSetterIFace));
			Marshal.StructureToPtr (native_iface, ifaceptr, false);
			GCHandle gch = (GCHandle) data;
			gch.Free ();
		}
コード例 #35
0
        public static void SetForegroundWindow(string SessId)
        {
            string windowName = "Session " + SessId + " - [24 x 80]";

            System.IntPtr hWnd = FindWindow(null, windowName);
            if (hWnd.ToInt64() != 0)
            {
                SetForegroundWindow(hWnd);
            }
        }
コード例 #36
0
            /// <summary>Initializes a new instance of the <see cref="Object"/> class.
            /// Internal usage: Constructor to actually call the native library constructors. C# subclasses
            /// must use the public constructor only.</summary>
            /// <param name="baseKlass">The pointer to the base native Eo class.</param>
            /// <param name="parent">The Efl.Object parent of this instance.</param>
            /// <param name="file">Name of the file from where the constructor is called.</param>
            /// <param name="line">Number of the line from where the constructor is called.</param>
            protected EoWrapper(IntPtr baseKlass, Efl.Object parent,
                                [CallerFilePath] string file = null,
                                [CallerLineNumber] int line  = 0)
            {
                generated = Efl.Eo.BindingEntity.IsBindingEntity(((object)this).GetType());
                IntPtr actual_klass = baseKlass;

                if (!generated)
                {
                    actual_klass = Efl.Eo.ClassRegister.GetInheritKlassOrRegister(baseKlass, ((object)this).GetType());
                }

                // Creation of the unfinalized Eo handle
                Eina.Log.Debug($"Instantiating from klass 0x{actual_klass.ToInt64():x}");
                System.IntPtr parent_ptr = System.IntPtr.Zero;
                if (parent != null)
                {
                    parent_ptr = parent.NativeHandle;
                }

                if (generated)
                {
                    handle = Efl.Eo.Globals._efl_add_internal_start(file, line, actual_klass, parent_ptr, 1, 0);
                }
                else
                {
                    handle = Efl.Eo.Globals._efl_add_internal_start_bindings(file, line, actual_klass, parent_ptr, 1, 0,
                                                                             Efl.Eo.Globals.efl_mono_avoid_top_level_constructor_callback_addr_get(),
                                                                             IntPtr.Zero);
                }

                if (handle == System.IntPtr.Zero)
                {
                    throw new Exception("Instantiation failed");
                }

                Eina.Log.Debug($"Eo instance right after internal_start 0x{handle.ToInt64():x} with refcount {Efl.Eo.Globals.efl_ref_count(handle)}");
                Eina.Log.Debug($"Parent was 0x{parent_ptr.ToInt64()}");

                // Creation of wrapper supervisor
                AddWrapperSupervisor();
            }
コード例 #37
0
ファイル: Timespec.cs プロジェクト: wfarr/grpc
        public Timespec Add(TimeSpan timeSpan)
        {
            long nanos        = tv_nsec.ToInt64() + (timeSpan.Ticks % TimeSpan.TicksPerSecond) * NanosPerTick;
            long overflow_sec = (nanos > NanosPerSecond) ? 1 : 0;

            Timespec result;

            result.tv_nsec = new IntPtr(nanos % NanosPerSecond);
            result.tv_sec  = new IntPtr(tv_sec.ToInt64() + (timeSpan.Ticks / TimeSpan.TicksPerSecond) + overflow_sec);
            return(result);
        }
コード例 #38
0
ファイル: Timespec.cs プロジェクト: hmings888/grpc
        public Timespec Add(TimeSpan timeSpan)
        {
            long nanos        = (long)tv_nsec + (timeSpan.Ticks % TimeSpan.TicksPerSecond) * NanosPerTick;
            long overflow_sec = (nanos > NanosPerSecond) ? 1 : 0;

            Timespec result;

            result.tv_nsec    = (int)(nanos % NanosPerSecond);
            result.tv_sec     = new IntPtr(tv_sec.ToInt64() + (timeSpan.Ticks / TimeSpan.TicksPerSecond) + overflow_sec);
            result.clock_type = GPRClockType.Realtime;
            return(result);
        }
コード例 #39
0
ファイル: EoWrapper.cs プロジェクト: conr2d/efl
            /// <summary>Finishes instantiating this object.
            /// Internal usage by generated code.</summary>
            protected void FinishInstantiation()
            {
                Eina.Log.Debug("calling efl_add_internal_end");
                var h = Efl.Eo.Globals._efl_add_end(handle, 1, 0);

                Eina.Log.Debug($"efl_add_end returned eo 0x{handle.ToInt64():x}");

                // if (h == IntPtr.Zero) // TODO
                // {
                // }

                handle = h;
            }
コード例 #40
0
 private static Engine.Joystick GetJoystick(System.IntPtr device)
 {
     foreach (Engine.Joystick joystick in engine.joysticks)
     {
         if (joystick != null)
         {
             if (joystick.id == device.ToInt64())
             {
                 return(joystick);
             }
         }
     }
     return(null);
 }
コード例 #41
0
ファイル: Edf.cs プロジェクト: jiahansu/UniEDF
        public static AllfData GetFloatData(EDFFILE file)
        {
            System.IntPtr ptr = edf_get_float_data(file);
            AllfData      data;

            if (ptr.ToInt64() != 0)
            {
                data = new AllfData(ptr);
            }
            else
            {
                data = null;
            }

            return(data);
        }
コード例 #42
0
ファイル: Edf.cs プロジェクト: jiahansu/UniEDF
        public static AllfData GetSampleCloseToTime(EDFFILE file, uint time)
        {
            System.IntPtr ptr = edf_get_sample_close_to_time(file, time);
            AllfData      data;

            if (ptr.ToInt64() != 0)
            {
                data = new AllfData(ptr);
            }
            else
            {
                data = null;
            }

            return(data);
        }
コード例 #43
0
 private static void DeviceRemoved(System.IntPtr context, System.IntPtr res, System.IntPtr sender, System.IntPtr device)
 {
     foreach (Engine.Joystick joystick in engine.joysticks)
     {
         if (joystick != null)
         {
             if (joystick.id == device.ToInt64())
             {
                 engine.joysticks [joystick.index] = null;
                 MacNative.IOHIDDeviceRegisterInputValueCallback(device, IntPtr.Zero, IntPtr.Zero);
                 MacNative.IOHIDDeviceUnscheduleFromRunLoop(device, runLoop, defaultLoopMode);
                 MacNative.IOHIDDeviceClose(device, IntPtr.Zero);
                 return;
             }
         }
     }
 }
コード例 #44
0
    // Use this for initialization
    void Start()
    {
        //pybullet = NativeMethods.b3ConnectSharedMemory(NativeConstants.SHARED_MEMORY_KEY);
        //if (NativeMethods.b3CanSubmitCommand(pybullet)==0)
        //{
        pybullet = NativeMethods.b3ConnectPhysicsDirect();
        //}

        //NativeMethods.b3SetAdditionalSearchPath(pybullet, "d:\\");

        Debug.Log("can submit command " + NativeMethods.b3CanSubmitCommand(pybullet));


        IntPtr cmd    = NativeMethods.b3InitResetSimulationCommand(pybullet);
        IntPtr status = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
        EnumSharedMemoryServerStatus statusType1;
        {
            IntPtr command = NativeMethods.b3InitPhysicsParamCommand(pybullet);
            NativeMethods.b3PhysicsParamSetGravity(command, 0, -10, 0);
            IntPtr statusHandle = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, command);
            statusType1 = (EnumSharedMemoryServerStatus)NativeMethods.b3GetStatusType(status);
            Debug.Log("set grav status " + statusType1);
        }

        int numBodies = NativeMethods.b3GetNumBodies(pybullet);

        {
            cmd = NativeMethods.b3LoadUrdfCommandInit(pybullet, "plane.urdf");
            Quaternion qq = Quaternion.Euler(-90, 0, 0);
            NativeMethods.b3LoadUrdfCommandSetStartOrientation(cmd, qq.x, qq.y, qq.z, qq.w);
            status      = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
            statusType1 = (EnumSharedMemoryServerStatus)NativeMethods.b3GetStatusType(status);
            Debug.Log("added plane " + statusType1);
        }

        {
            cmd = NativeMethods.b3LoadUrdfCommandInit(pybullet, "quadruped/minitaur.urdf");
            NativeMethods.b3LoadUrdfCommandSetStartPosition(cmd, 0, 20, 0);
            Quaternion q = Quaternion.Euler(35, 0, 0);
            NativeMethods.b3LoadUrdfCommandSetStartOrientation(cmd, q.x, q.y, q.z, q.w);
            status      = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
            statusType1 = (EnumSharedMemoryServerStatus)NativeMethods.b3GetStatusType(status);
            Debug.Log("added minitaur " + statusType1);
        }

        m_cubeUid = NativeMethods.b3GetStatusBodyIndex(status);
        Debug.Log("minitaur " + m_cubeUid);
        EnumSharedMemoryServerStatus statusType = (EnumSharedMemoryServerStatus)NativeMethods.b3GetStatusType(status);

        if (statusType == (EnumSharedMemoryServerStatus)EnumSharedMemoryServerStatus.CMD_URDF_LOADING_COMPLETED)
        {
            numBodies = NativeMethods.b3GetNumBodies(pybullet);
            Debug.Log("Numbodies " + numBodies);
            cmd        = NativeMethods.b3InitRequestVisualShapeInformation(pybullet, m_cubeUid);
            status     = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
            statusType = (EnumSharedMemoryServerStatus)NativeMethods.b3GetStatusType(status);
            Debug.Log("StatusType " + statusType);
            if (statusType == EnumSharedMemoryServerStatus.CMD_VISUAL_SHAPE_INFO_COMPLETED ||
                statusType == EnumSharedMemoryServerStatus.CMD_VISUAL_SHAPE_UPDATE_COMPLETED)
            {
                b3VisualShapeInformation visuals = new b3VisualShapeInformation();
                NativeMethods.b3GetVisualShapeInformation(pybullet, ref visuals);
                Debug.Log("visuals.m_numVisualShapes=" + visuals.m_numVisualShapes);
                System.IntPtr visualPtr = visuals.m_visualShapeData;

                robot.bodies = new Body[visuals.m_numVisualShapes];

                for (int s = 0; s < visuals.m_numVisualShapes; s++)
                {
                    b3VisualShapeData visual = (b3VisualShapeData)Marshal.PtrToStructure(visualPtr, typeof(b3VisualShapeData));
                    visualPtr = new IntPtr(visualPtr.ToInt64() + (Marshal.SizeOf(typeof(b3VisualShapeData))));
                    Vector3 scale;
                    scale.x = (float)visual.m_dimensions[0];
                    scale.y = (float)visual.m_dimensions[1];
                    scale.z = (float)visual.m_dimensions[2];

                    Debug.Log("visual.m_visualGeometryType = " + (eUrdfGeomTypes)visual.m_visualGeometryType);
                    Debug.Log("visual.m_dimensions" + scale.x + "," + scale.y + "," + scale.z);

                    Vector3 pos;
                    pos.x = (float)visual.m_localVisualFrame[0];
                    pos.y = (float)visual.m_localVisualFrame[1];
                    pos.z = (float)visual.m_localVisualFrame[2];
                    Quaternion rot;
                    rot.x = (float)visual.m_localVisualFrame[3];
                    rot.y = (float)visual.m_localVisualFrame[4];
                    rot.z = (float)visual.m_localVisualFrame[5];
                    rot.w = (float)visual.m_localVisualFrame[6];

                    robot.bodies[s] = CreateShape(visual, "cube", pos, rot, scale);

                    if (visual.m_visualGeometryType == (int)eUrdfGeomTypes.GEOM_MESH)
                    {
                        Debug.Log("visual.m_meshAssetFileName=" + visual.m_meshAssetFileName);
                    }
                }
            }
            if (numBodies > 0)
            {
                b3BodyInfo info = new b3BodyInfo();
                NativeMethods.b3GetBodyInfo(pybullet, 0, ref info);
            }
        }
    }
コード例 #45
0
        public static IEnumerable <object> Get_NetLocalGroupMember(Args_Get_NetLocalGroupMember args = null)
        {
            if (args == null)
            {
                args = new Args_Get_NetLocalGroupMember();
            }

            var LogonToken = IntPtr.Zero;

            if (args.Credential != null)
            {
                LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                {
                    Credential = args.Credential
                });
            }

            var LocalGroupMembers = new List <object>();

            foreach (var Computer in args.ComputerName)
            {
                if (args.Method == MethodType.API)
                {
                    // if we're using the Netapi32 NetLocalGroupGetMembers API call to get the local group information
                    // arguments for NetLocalGroupGetMembers
                    var QueryLevel   = 2;
                    var PtrInfo      = IntPtr.Zero;
                    var EntriesRead  = 0;
                    var TotalRead    = 0;
                    var ResumeHandle = IntPtr.Zero;

                    // get the local user information
                    var Result = NativeMethods.NetLocalGroupGetMembers(Computer, args.GroupName, QueryLevel, out PtrInfo, -1, out EntriesRead, out TotalRead, ResumeHandle);

                    // locate the offset of the initial intPtr
                    var Offset = PtrInfo.ToInt64();

                    var Members = new List <object>();

                    // 0 = success
                    if ((Result == 0) && (Offset > 0))
                    {
                        // Work out how much to increment the pointer by finding out the size of the structure
                        var Increment = Marshal.SizeOf(typeof(LOCALGROUP_MEMBERS_INFO_2));

                        // parse all the result structures
                        for (var i = 0; (i < EntriesRead); i++)
                        {
                            // create a new int ptr at the given offset and cast the pointer as our result structure
                            var NewIntPtr = new System.IntPtr(Offset);
                            var Info      = (LOCALGROUP_MEMBERS_INFO_2)Marshal.PtrToStructure(NewIntPtr, typeof(LOCALGROUP_MEMBERS_INFO_2));

                            Offset  = NewIntPtr.ToInt64();
                            Offset += Increment;

                            var SidString = "";
                            var Result2   = NativeMethods.ConvertSidToStringSid(Info.lgrmi2_sid, out SidString);
                            var LastError = System.Runtime.InteropServices.Marshal.GetLastWin32Error();

                            if (!Result2)
                            {
                                Logger.Write_Verbose($@"[Get-NetLocalGroupMember] Error: {new System.ComponentModel.Win32Exception((int)Result).Message}");
                            }
                            else
                            {
                                var Member = new LocalGroupMemberAPI
                                {
                                    ComputerName = Computer,
                                    GroupName    = args.GroupName,
                                    MemberName   = Info.lgrmi2_domainandname,
                                    SID          = SidString,
                                    IsGroup      = Info.lgrmi2_sidusage == SID_NAME_USE.SidTypeGroup
                                };
                                Members.Add(Member);
                            }
                        }

                        // free up the result buffer
                        NativeMethods.NetApiBufferFree(PtrInfo);

                        // try to extract out the machine SID by using the -500 account as a reference
                        var MachineSid = (Members.FirstOrDefault(x => (x as LocalGroupMemberAPI).SID.IsRegexMatch(".*-500") || (x as LocalGroupMemberAPI).SID.IsRegexMatch(".*-501")) as LocalGroupMemberAPI).SID;
                        if (MachineSid != null)
                        {
                            MachineSid = MachineSid.Substring(0, MachineSid.LastIndexOf('-'));

                            foreach (LocalGroupMemberAPI member in Members)
                            {
                                if (member.SID.IsRegexMatch(MachineSid))
                                {
                                    member.IsDomain = "false";
                                }
                                else
                                {
                                    member.IsDomain = "true";
                                }
                            }
                        }
                        else
                        {
                            foreach (LocalGroupMemberAPI member in Members)
                            {
                                if (!member.SID.IsRegexMatch("S-1-5-21"))
                                {
                                    member.IsDomain = "false";
                                }
                                else
                                {
                                    member.IsDomain = "UNKNOWN";
                                }
                            }
                        }
                        LocalGroupMembers.AddRange(Members);
                    }
                    else
                    {
                        Logger.Write_Verbose($@"[Get-NetLocalGroupMember] Error: {new System.ComponentModel.Win32Exception((int)Result).Message}");
                    }
                }
                else
                {
                    // otherwise we're using the WinNT service provider
                    try
                    {
                        var         GroupProvider = new System.DirectoryServices.DirectoryEntry($@"WinNT://{Computer}/{args.GroupName},group");
                        IEnumerable Members       = (IEnumerable)GroupProvider.Invoke("Members");
                        foreach (var obj in Members)
                        {
                            var LocalUser = new System.DirectoryServices.DirectoryEntry(obj);
                            var Member    = new LocalGroupMemberWinNT
                            {
                                ComputerName = Computer,
                                GroupName    = args.GroupName
                            };

                            var AdsPath = LocalUser.InvokeGet("AdsPath").ToString().Replace("WinNT://", "");
                            var IsGroup = LocalUser.SchemaClassName.IsLikeMatch("group");

                            bool   MemberIsDomain;
                            string Name;
                            if (Regex.Matches(AdsPath, "/").Count == 1)
                            {
                                // DOMAIN\user
                                MemberIsDomain = true;
                                Name           = AdsPath.Replace(@"/", @"\");
                            }
                            else
                            {
                                // DOMAIN\machine\user
                                MemberIsDomain = false;
                                Name           = AdsPath.Substring(AdsPath.IndexOf('/') + 1).Replace(@"/", @"\");
                            }

                            Member.AccountName = Name;
                            Member.SID         = new System.Security.Principal.SecurityIdentifier((byte[])LocalUser.InvokeGet("ObjectSID"), 0).Value;
                            Member.IsGroup     = IsGroup;
                            Member.IsDomain    = MemberIsDomain;

                            LocalGroupMembers.Add(Member);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[Get-NetLocalGroupMember] Error for {Computer} : {e}");
                    }
                }
            }

            if (LogonToken != IntPtr.Zero)
            {
                InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken);
            }
            return(LocalGroupMembers);
        }
コード例 #46
0
ファイル: GDALMemDataset.cs プロジェクト: tabinfl/gdal
    public static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            usage();
        }

        Gdal.AllRegister();

        Bitmap bmp = new Bitmap(args[0]);

        // set up MEM driver to read bitmap data
        int      bandCount   = 1;
        int      pixelOffset = 1;
        DataType dataType    = DataType.GDT_Byte;

        switch (bmp.PixelFormat)
        {
        case PixelFormat.Format16bppGrayScale:
            dataType    = DataType.GDT_Int16;
            bandCount   = 1;
            pixelOffset = 2;
            break;

        case PixelFormat.Format24bppRgb:
            dataType    = DataType.GDT_Byte;
            bandCount   = 3;
            pixelOffset = 3;
            break;

        case PixelFormat.Format32bppArgb:
            dataType    = DataType.GDT_Byte;
            bandCount   = 4;
            pixelOffset = 4;
            break;

        case PixelFormat.Format48bppRgb:
            dataType    = DataType.GDT_UInt16;
            bandCount   = 3;
            pixelOffset = 6;
            break;

        case PixelFormat.Format64bppArgb:
            dataType    = DataType.GDT_UInt16;
            bandCount   = 4;
            pixelOffset = 8;
            break;

        default:
            Console.WriteLine("Invalid pixel format " + bmp.PixelFormat.ToString());
            break;
        }

        // Use GDAL raster reading methods to read the image data directly into the Bitmap
        BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);

        int stride = bitmapData.Stride;

        System.IntPtr buf = bitmapData.Scan0;

        try
        {
            Driver drvmem = Gdal.GetDriverByName("MEM");
            // create a MEM dataset
            Dataset ds = drvmem.Create("", bmp.Width, bmp.Height, 0, dataType, null);
            // add bands in a reverse order
            for (int i = 1; i <= bandCount; i++)
            {
                ds.AddBand(dataType, new string[] { "DATAPOINTER=" + Convert.ToString(buf.ToInt64() + bandCount - i), "PIXELOFFSET=" + pixelOffset, "LINEOFFSET=" + stride });
            }

            // display parameters
            Console.WriteLine("Raster dataset parameters:");
            Console.WriteLine("  RasterCount: " + ds.RasterCount);
            Console.WriteLine("  RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");

            // write dataset to tif file
            Driver drv = Gdal.GetDriverByName("GTiff");

            if (drv == null)
            {
                Console.WriteLine("Can't get driver.");
                System.Environment.Exit(-1);
            }

            drv.CreateCopy("sample2.tif", ds, 0, null, null, null);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            bmp.UnlockBits(bitmapData);
        }
    }
コード例 #47
0
ファイル: Allocation.cs プロジェクト: bblpny/csharputilities
 public sealed override string ToString()
 {
     return(IntPtr.Size == 4 ? Address0.ToInt32().ToString("X8") : Address0.ToInt64().ToString("X16"));
 }
コード例 #48
0
ファイル: MyMapping.cs プロジェクト: viktorius/Viktor
 internal void WriteAndPosition <T>(T[] data, int count, int offset = 0) where T : struct
 {
     m_dataPointer = Utilities.Write(m_dataPointer, data, offset, count);
     Debug.Assert((m_dataPointer.ToInt64() - m_dataBox.DataPointer.ToInt64()) <= m_bufferSize);
 }
コード例 #49
0
ファイル: MyMapping.cs プロジェクト: viktorius/Viktor
 internal void WriteAndPosition <T>(ref T data) where T : struct
 {
     m_dataPointer = Utilities.WriteAndPosition(m_dataPointer, ref data);
     Debug.Assert((m_dataPointer.ToInt64() - m_dataBox.DataPointer.ToInt64()) <= m_bufferSize);
 }
コード例 #50
0
        public static IEnumerable <ShareInfo> Get_NetShare(Args_Get_NetShare args = null)
        {
            if (args == null)
            {
                args = new Args_Get_NetShare();
            }

            var shareInfos = new List <ShareInfo>();

            var LogonToken = IntPtr.Zero;

            if (args.Credential != null)
            {
                LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                {
                    Credential = args.Credential
                });
            }
            foreach (var Computer in args.ComputerName)
            {
                // arguments for NetShareEnum
                var QueryLevel   = 1;
                var PtrInfo      = IntPtr.Zero;
                var EntriesRead  = 0;
                var TotalRead    = 0;
                var ResumeHandle = 0;

                // get the raw share information
                var Result = NativeMethods.NetShareEnum(Computer, QueryLevel, ref PtrInfo, MAX_PREFERRED_LENGTH, ref EntriesRead, ref TotalRead, ref ResumeHandle);

                // locate the offset of the initial intPtr
                var Offset = PtrInfo.ToInt64();

                // 0 = success
                if ((Result == 0) && (Offset > 0))
                {
                    // work out how much to increment the pointer by finding out the size of the structure
                    var Increment = Marshal.SizeOf(typeof(SHARE_INFO_1));

                    // parse all the result structures
                    for (var i = 0; (i < EntriesRead); i++)
                    {
                        // create a new int ptr at the given offset and cast the pointer as our result structure
                        var NewIntPtr = new System.IntPtr(Offset);
                        var Info      = (SHARE_INFO_1)Marshal.PtrToStructure(NewIntPtr, typeof(SHARE_INFO_1));

                        // return all the sections of the structure - have to do it this way for V2
                        shareInfos.Add(new ShareInfo
                        {
                            Name         = Info.shi1_netname,
                            Type         = Info.shi1_type,
                            Remark       = Info.shi1_remark,
                            ComputerName = Computer
                        });
                        Offset  = NewIntPtr.ToInt64();
                        Offset += Increment;
                    }

                    // free up the result buffer
                    NativeMethods.NetApiBufferFree(PtrInfo);
                }
                else
                {
                    Logger.Write_Verbose($@"[Get-NetShare] Error: {new System.ComponentModel.Win32Exception((int)Result).Message}");
                }
            }

            if (LogonToken != IntPtr.Zero)
            {
                InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken);
            }
            return(shareInfos);
        }
コード例 #51
0
    //TODO deal with loading status
    public int LoadUrdfAndGetBodyIdx(string modelName, Vector3 p, Quaternion qq)
    {
        IntPtr cmd = NativeMethods.b3LoadUrdfCommandInit(_native, modelName);

        //IntPtr cmd = NativeMethods.b3LoadMJCFCommandInit(_native, modelName);

        NativeMethods.b3LoadUrdfCommandSetStartOrientation(cmd, qq.x, qq.y, qq.z, qq.w);
        NativeMethods.b3LoadUrdfCommandSetStartPosition(cmd, p.x, p.y, p.z);
        IntPtr status  = NativeMethods.b3SubmitClientCommandAndWaitStatus(_native, cmd);
        int    bodyIdx = NativeMethods.b3GetStatusBodyIndex(status);

        Debug.Log("body index " + bodyIdx);
        cmd    = NativeMethods.b3InitRequestVisualShapeInformation(_native, bodyIdx);
        status = NativeMethods.b3SubmitClientCommandAndWaitStatus(_native, cmd);
        EnumSharedMemoryServerStatus statusType = (EnumSharedMemoryServerStatus)NativeMethods.b3GetStatusType(status);

        if (statusType == EnumSharedMemoryServerStatus.CMD_VISUAL_SHAPE_INFO_COMPLETED ||
            statusType == EnumSharedMemoryServerStatus.CMD_VISUAL_SHAPE_UPDATE_COMPLETED)
        {
            b3VisualShapeInformation visuals = new b3VisualShapeInformation();
            NativeMethods.b3GetVisualShapeInformation(_native, ref visuals);
            Debug.Log("visuals.m_numVisualShapes=" + visuals.m_numVisualShapes);
            int           numVisualShapes = visuals.m_numVisualShapes;
            System.IntPtr visualPtr       = visuals.m_visualShapeData;

            //robot.bodies = new Body[visuals.m_numVisualShapes];

            for (int s = 0; s < visuals.m_numVisualShapes; s++)
            {
                b3VisualShapeData visual = (b3VisualShapeData)Marshal.PtrToStructure(visualPtr, typeof(b3VisualShapeData));
                visualPtr = new IntPtr(visualPtr.ToInt64() + (Marshal.SizeOf(typeof(b3VisualShapeData))));
                Vector3 scale;
                scale.x = (float)visual.m_dimensions[0];
                scale.y = (float)visual.m_dimensions[1];
                scale.z = (float)visual.m_dimensions[2];

                Debug.Log("visual.m_visualGeometryType =" + (eUrdfGeomTypes)visual.m_visualGeometryType +
                          " linkIndex=" + visual.m_linkIndex + " id=" + visual.m_objectUniqueId);

                Vector3 pos;
                pos.x = (float)visual.m_localVisualFrame[0];
                pos.y = (float)visual.m_localVisualFrame[1];
                pos.z = (float)visual.m_localVisualFrame[2];
                Quaternion rot;
                rot.x = (float)visual.m_localVisualFrame[3];
                rot.y = (float)visual.m_localVisualFrame[4];
                rot.z = (float)visual.m_localVisualFrame[5];
                rot.w = (float)visual.m_localVisualFrame[6];

                //robot.bodies[s] = CreateShape(visual, "cube", pos, rot, scale);

                if (visual.m_visualGeometryType == (int)eUrdfGeomTypes.GEOM_MESH)
                {
                    Debug.Log("visual.m_meshAssetFileName=" + visual.m_meshAssetFileName);
                }
            }
        }

        int numJoints = NativeMethods.b3GetNumJoints(_native, bodyIdx);

        Dictionary <string, int> jointNameToId = new Dictionary <string, int>();

        for (int i = 0; i < numJoints; i++)
        {
            b3JointInfo jointInfo = new b3JointInfo();
            NativeMethods.b3GetJointInfo(_native, bodyIdx, i, ref jointInfo);
            jointNameToId.Add(jointInfo.m_jointName, i);
            Debug.Log("Joint name " + jointInfo.m_jointName + " Link name " + jointInfo.m_linkName);
        }

        //NativeMethods.collisionshape(_native, bodyIdx);

        return(bodyIdx);
    }
コード例 #52
0
ファイル: GetNetSession.cs プロジェクト: t43Wiu6/SharpView
        public static IEnumerable <SessionInfo> Get_NetSession(Args_Get_NetSession args = null)
        {
            if (args == null)
            {
                args = new Args_Get_NetSession();
            }

            var LogonToken = IntPtr.Zero;

            if (args.Credential != null)
            {
                LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                {
                    Credential = args.Credential
                });
            }

            var SessionInfos = new List <SessionInfo>();

            foreach (var Computer in args.ComputerName)
            {
                // arguments for NetSessionEnum
                var QueryLevel   = 10;
                var PtrInfo      = IntPtr.Zero;
                var EntriesRead  = 0;
                var TotalRead    = 0;
                var ResumeHandle = 0;
                var UserName     = string.Empty;

                // get session information
                var Result = NativeMethods.NetSessionEnum(Computer, string.Empty, UserName, QueryLevel, out PtrInfo, -1, ref EntriesRead, ref TotalRead, ref ResumeHandle);

                // locate the offset of the initial intPtr
                var Offset = PtrInfo.ToInt64();

                // 0 = success
                if ((Result == 0) && (Offset > 0))
                {
                    // work out how much to increment the pointer by finding out the size of the structure
                    var Increment = Marshal.SizeOf(typeof(SESSION_INFO_10));

                    // parse all the result structures
                    for (var i = 0; (i < EntriesRead); i++)
                    {
                        // create a new int ptr at the given offset and cast the pointer as our result structure
                        var NewIntPtr = new System.IntPtr(Offset);
                        var Info      = (SESSION_INFO_10)Marshal.PtrToStructure(NewIntPtr, typeof(SESSION_INFO_10));

                        // return all the sections of the structure - have to do it this way for V2
                        var Session = new SessionInfo
                        {
                            ComputerName = Computer,
                            CName        = Info.sesi10_cname,
                            UserName     = Info.sesi10_username,
                            Time         = Info.sesi502_time,
                            IdleTime     = Info.sesi502_idle_time
                        };
                        Offset  = NewIntPtr.ToInt64();
                        Offset += Increment;
                        SessionInfos.Add(Session);
                    }

                    // free up the result buffer
                    NativeMethods.NetApiBufferFree(PtrInfo);
                }
                else
                {
                    Logger.Write_Verbose($@"[Get-NetSession] Error: {new System.ComponentModel.Win32Exception((int)Result).Message}");
                }
            }

            if (LogonToken != IntPtr.Zero)
            {
                InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken);
            }
            return(SessionInfos);
        }
コード例 #53
0
ファイル: GetNetLoggedon.cs プロジェクト: t43Wiu6/SharpView
        public static IEnumerable <LoggedOnUserInfo> Get_NetLoggedon(Args_Get_NetLoggedon args = null)
        {
            if (args == null)
            {
                args = new Args_Get_NetLoggedon();
            }

            var LogonToken = IntPtr.Zero;

            if (args.Credential != null)
            {
                LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                {
                    Credential = args.Credential
                });
            }

            var LoggedOns = new List <LoggedOnUserInfo>();

            foreach (var Computer in args.ComputerName)
            {
                // declare the reference variables
                var QueryLevel   = 1;
                var PtrInfo      = IntPtr.Zero;
                var EntriesRead  = 0;
                var TotalRead    = 0;
                var ResumeHandle = 0;

                // get logged on user information
                var Result = NativeMethods.NetWkstaUserEnum(Computer, QueryLevel, out PtrInfo, -1, out EntriesRead, out TotalRead, ref ResumeHandle);

                // locate the offset of the initial intPtr
                var Offset = PtrInfo.ToInt64();

                // 0 = success
                if ((Result == 0) && (Offset > 0))
                {
                    // work out how much to increment the pointer by finding out the size of the structure
                    var Increment = Marshal.SizeOf(typeof(WKSTA_USER_INFO_1));

                    // parse all the result structures
                    for (var i = 0; (i < EntriesRead); i++)
                    {
                        // create a new int ptr at the given offset and cast the pointer as our result structure
                        var NewIntPtr = new System.IntPtr(Offset);
                        var Info      = (WKSTA_USER_INFO_1)Marshal.PtrToStructure(NewIntPtr, typeof(WKSTA_USER_INFO_1));

                        // return all the sections of the structure - have to do it this way for V2
                        LoggedOns.Add(new LoggedOnUserInfo
                        {
                            UserName     = Info.wkui1_username,
                            LogonDomain  = Info.wkui1_logon_domain,
                            AuthDomains  = Info.wkui1_oth_domains,
                            LogonServer  = Info.wkui1_logon_server,
                            ComputerName = Computer
                        });
                        Offset  = NewIntPtr.ToInt64();
                        Offset += Increment;
                    }

                    // free up the result buffer
                    NativeMethods.NetApiBufferFree(PtrInfo);
                }
                else
                {
                    Logger.Write_Verbose($@"[Get-NetLoggedon] Error: {new System.ComponentModel.Win32Exception((int)Result).Message}");
                }
            }

            if (LogonToken != IntPtr.Zero)
            {
                InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken);
            }
            return(LoggedOns);
        }
コード例 #54
0
ファイル: NativePtr.cs プロジェクト: jaypaw549/MimiTools
 public NativePtr Add(NativePtr other)
 => new NativePtr(new System.IntPtr(_value.ToInt64() + other._value.ToInt64()));
コード例 #55
0
    // Use this for initialization
    void Start()
    {
        text = GetComponent <Text>();


        pybullet = NativeMethods.b3ConnectSharedMemory(NativeConstants.SHARED_MEMORY_KEY);
        if (NativeMethods.b3CanSubmitCommand(pybullet) == 0)
        {
            pybullet = NativeMethods.b3ConnectPhysicsDirect();
        }



        IntPtr cmd    = NativeMethods.b3InitResetSimulationCommand(pybullet);
        IntPtr status = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, cmd);

        {
            IntPtr command = NativeMethods.b3InitPhysicsParamCommand(pybullet);
            NativeMethods.b3PhysicsParamSetGravity(command, 0, -10, 0);
            IntPtr statusHandle = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, command);
        }

        int numBodies = NativeMethods.b3GetNumBodies(pybullet);

        Debug.Log(numBodies);
        {
            cmd = NativeMethods.b3LoadUrdfCommandInit(pybullet, "plane.urdf");
            Quaternion qq = Quaternion.Euler(-90, 0, 0);
            NativeMethods.b3LoadUrdfCommandSetStartOrientation(cmd, qq.x, qq.y, qq.z, qq.w);
            status = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
        }


        cmd = NativeMethods.b3LoadUrdfCommandInit(pybullet, "cube.urdf");
        NativeMethods.b3LoadUrdfCommandSetStartPosition(cmd, 0, 20, 0);
        Quaternion q = Quaternion.Euler(35, 0, 0);

        NativeMethods.b3LoadUrdfCommandSetStartOrientation(cmd, q.x, q.y, q.z, q.w);
        status    = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
        m_cubeUid = NativeMethods.b3GetStatusBodyIndex(status);

        EnumSharedMemoryServerStatus statusType = (EnumSharedMemoryServerStatus)NativeMethods.b3GetStatusType(status);

        if (statusType == (EnumSharedMemoryServerStatus)EnumSharedMemoryServerStatus.CMD_URDF_LOADING_COMPLETED)
        {
            numBodies  = NativeMethods.b3GetNumBodies(pybullet);
            text.text  = numBodies.ToString();
            cmd        = NativeMethods.b3InitRequestVisualShapeInformation(pybullet, m_cubeUid);
            status     = NativeMethods.b3SubmitClientCommandAndWaitStatus(pybullet, cmd);
            statusType = (EnumSharedMemoryServerStatus)NativeMethods.b3GetStatusType(status);

            if (statusType == (EnumSharedMemoryServerStatus)EnumSharedMemoryServerStatus.CMD_VISUAL_SHAPE_INFO_COMPLETED)
            {
                b3VisualShapeInformation visuals = new b3VisualShapeInformation();
                NativeMethods.b3GetVisualShapeInformation(pybullet, ref visuals);
                System.Console.WriteLine("visuals.m_numVisualShapes=" + visuals.m_numVisualShapes);
                System.IntPtr visualPtr = visuals.m_visualShapeData;

                for (int s = 0; s < visuals.m_numVisualShapes; s++)
                {
                    b3VisualShapeData visual = (b3VisualShapeData)Marshal.PtrToStructure(visualPtr, typeof(b3VisualShapeData));
                    visualPtr = new IntPtr(visualPtr.ToInt64() + (Marshal.SizeOf(typeof(b3VisualShapeData))));
                    double x = visual.m_dimensions[0];
                    double y = visual.m_dimensions[1];
                    double z = visual.m_dimensions[2];
                    System.Console.WriteLine("visual.m_visualGeometryType = " + visual.m_visualGeometryType);
                    System.Console.WriteLine("visual.m_dimensions" + x + "," + y + "," + z);
                    if (visual.m_visualGeometryType == (int)eUrdfGeomTypes.GEOM_MESH)
                    {
                        System.Console.WriteLine("visual.m_meshAssetFileName=" + visual.m_meshAssetFileName);
                        text.text = visual.m_meshAssetFileName;
                    }
                }
            }
            if (numBodies > 0)
            {
                b3BodyInfo info = new b3BodyInfo();
                NativeMethods.b3GetBodyInfo(pybullet, 0, ref info);

                text.text = info.m_baseName;
            }
        }
    }
コード例 #56
0
ファイル: GetNetLocalGroup.cs プロジェクト: t43Wiu6/SharpView
        public static IEnumerable <object> Get_NetLocalGroup(Args_Get_NetLocalGroup args = null)
        {
            if (args == null)
            {
                args = new Args_Get_NetLocalGroup();
            }

            var LogonToken = IntPtr.Zero;

            if (args.Credential != null)
            {
                LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                {
                    Credential = args.Credential
                });
            }

            var LocalGroups = new List <object>();

            foreach (var Computer in args.ComputerName)
            {
                if (args.Method == MethodType.API)
                {
                    // if we're using the Netapi32 NetLocalGroupEnum API call to get the local group information
                    // arguments for NetLocalGroupEnum
                    var QueryLevel   = 1;
                    var PtrInfo      = IntPtr.Zero;
                    var EntriesRead  = 0;
                    var TotalRead    = 0;
                    var ResumeHandle = 0;

                    // get the local user information
                    var Result = NativeMethods.NetLocalGroupEnum(Computer, QueryLevel, out PtrInfo, MAX_PREFERRED_LENGTH, out EntriesRead, out TotalRead, ref ResumeHandle);

                    // locate the offset of the initial intPtr
                    var Offset = PtrInfo.ToInt64();

                    // 0 = success
                    if ((Result == 0) && (Offset > 0))
                    {
                        // Work out how much to increment the pointer by finding out the size of the structure
                        var Increment = Marshal.SizeOf(typeof(LOCALGROUP_INFO_1));

                        // parse all the result structures
                        for (var i = 0; (i < EntriesRead); i++)
                        {
                            // create a new int ptr at the given offset and cast the pointer as our result structure
                            var NewIntPtr = new System.IntPtr(Offset);
                            var Info      = (LOCALGROUP_INFO_1)Marshal.PtrToStructure(NewIntPtr, typeof(LOCALGROUP_INFO_1));

                            LocalGroups.Add(new LocalGroupAPI
                            {
                                ComputerName = Computer,
                                GroupName    = Info.lgrpi1_name,
                                Comment      = Info.lgrpi1_comment
                            });
                            Offset  = NewIntPtr.ToInt64();
                            Offset += Increment;
                        }
                        // free up the result buffer
                        NativeMethods.NetApiBufferFree(PtrInfo);
                    }
                    else
                    {
                        Logger.Write_Verbose($@"[Get-NetLocalGroup] Error: {new System.ComponentModel.Win32Exception((int)Result).Message}");
                    }
                }
                else
                {
                    // otherwise we're using the WinNT service provider
                    var ComputerProvider = new System.DirectoryServices.DirectoryEntry($@"WinNT://{Computer},computer");
                    foreach (System.DirectoryServices.DirectoryEntry LocalGroup in ComputerProvider.Children)
                    {
                        if (LocalGroup.SchemaClassName.Equals("group", StringComparison.OrdinalIgnoreCase))
                        {
                            var Group = new LocalGroupWinNT
                            {
                                ComputerName = Computer,
                                GroupName    = LocalGroup.Name,
                                SID          = new System.Security.Principal.SecurityIdentifier((byte[])LocalGroup.InvokeGet("objectsid"), 0).Value,
                                Comment      = LocalGroup.InvokeGet("Description").ToString()
                            };
                            LocalGroups.Add(Group);
                        }
                    }
                }
            }

            if (LogonToken != IntPtr.Zero)
            {
                InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken);
            }
            return(LocalGroups);
        }
コード例 #57
0
 static public void AddPtr(ref System.IntPtr p, int offset)
 {
     p = new System.IntPtr(p.ToInt64() + offset);
 }
コード例 #58
0
ファイル: SpanHelpers.cs プロジェクト: wellsjiang/corefx
        /// <summary>
        /// Implements the copy functionality used by Span and ReadOnlySpan.
        ///
        /// NOTE: Fast span implements TryCopyTo in corelib and therefore this implementation
        ///       is only used by portable span. The code must live in code that only compiles
        ///       for portable span which means either each individual span implementation
        ///       of this shared code file. Other shared SpanHelper.X.cs files are compiled
        ///       for both portable and fast span implementations.
        /// </summary>
        public static unsafe void CopyTo <T>(ref T dst, int dstLength, ref T src, int srcLength)
        {
            IntPtr srcMinusDst       = Unsafe.ByteOffset <T>(ref dst, ref src);
            bool   srcGreaterThanDst = (sizeof(IntPtr) == sizeof(int)) ? srcMinusDst.ToInt32() >= 0 : srcMinusDst.ToInt64() >= 0;
            IntPtr tailDiff;

            if (srcGreaterThanDst)
            {
                // If the start of source is greater than the start of destination, then we need to calculate
                // the different between the end of destination relative to the start of source.
                tailDiff = Unsafe.ByteOffset <T>(ref Unsafe.Add <T>(ref dst, dstLength), ref src);
            }
            else
            {
                // If the start of source is less than the start of destination, then we need to calculate
                // the different between the end of source relative to the start of destunation.
                tailDiff = Unsafe.ByteOffset <T>(ref Unsafe.Add <T>(ref src, srcLength), ref dst);
            }

            // If the source is entirely before or entirely after the destination and the type inside the span is not
            // itself a reference type or containing reference types, then we can do a simple block copy of the data.
            bool isOverlapped = (sizeof(IntPtr) == sizeof(int)) ? tailDiff.ToInt32() < 0 : tailDiff.ToInt64() < 0;

            if (!isOverlapped && !SpanHelpers.IsReferenceOrContainsReferences <T>())
            {
                ref byte dstBytes  = ref Unsafe.As <T, byte>(ref dst);
                ref byte srcBytes  = ref Unsafe.As <T, byte>(ref src);
コード例 #59
-1
        public SharedMemory(string name, IntPtr size)
        {
            mmf = MemoryMappedFile.OpenExisting(name + "_CONNECT_DATA");

            mmva = mmf.CreateViewAccessor();
            if (mmf.SafeMemoryMappedFileHandle.IsInvalid)
                throw new MySqlException("Cannot open file mapping " + name);
            mmvs = mmf.CreateViewStream(0L, size.ToInt64());
            mmva = mmf.CreateViewAccessor(0L, size.ToInt64());
        }