Ejemplo n.º 1
0
        /// <summary>https://stackoverflow.com/a/54732489</summary>
        static public System.IntPtr Allocate(System.Diagnostics.ProcessModule processModule, System.Int32 size)
        {
            Memory.GetSystemInfo(out var systemInfo);

            var minimum = processModule.BaseAddress.ToInt64() > processModule.ModuleMemorySize - System.Int32.MinValue ? Math.Ceiling(processModule.BaseAddress + System.Int32.MinValue + processModule.ModuleMemorySize, systemInfo.AllocationGranularity) : System.IntPtr.Zero;
            var maximum = processModule.BaseAddress.ToInt64() < (System.Int64.MaxValue - System.Int32.MaxValue) ? Math.Floor(processModule.BaseAddress + System.Int32.MaxValue, systemInfo.AllocationGranularity) : new System.IntPtr(System.Int64.MaxValue);

            while (minimum.ToInt64() < maximum.ToInt64())
            {
                if (Memory.VirtualQuery(minimum, out var memoryBasicInformation, new System.IntPtr(System.Runtime.CompilerServices.Unsafe.SizeOf <MemoryBasicInformation>())) == System.IntPtr.Zero)
                {
                    return(System.IntPtr.Zero);
                }

                minimum = new System.IntPtr(memoryBasicInformation.BaseAddress.ToInt64() + memoryBasicInformation.RegionSize.ToInt64());

                if (memoryBasicInformation.State == MemoryBasicInformation.States.MemFree)
                {
                    var baseAddress = Math.Ceiling(memoryBasicInformation.BaseAddress, systemInfo.AllocationGranularity);

                    // If rounding has not changed regions and the region is at least the specified size
                    if (baseAddress.ToInt64() < minimum.ToInt64() && (minimum.ToInt64() - baseAddress.ToInt64()) >= size)
                    {
                        var allocation = Memory.VirtualAlloc(baseAddress, new System.IntPtr(size), AllocationTypes.MemCommit | AllocationTypes.MemReserve, MemoryProtectionConstants.PageExecuteReadWrite);

                        if (allocation != System.IntPtr.Zero)
                        {
                            return(allocation);
                        }
                    }
                }
            }

            return(System.IntPtr.Zero);
        }
Ejemplo n.º 2
0
 internal static void MemoryCopy(System.IntPtr dst, System.IntPtr src, int count)
 {
     Debug.Assert(dst != src, "dst and src are the same");
     Debug.Assert(dst.ToInt64() < src.ToInt64() || src.ToInt64() + count <= dst.ToInt64(), "overlapping region dst");
     Debug.Assert(src.ToInt64() < dst.ToInt64() || dst.ToInt64() + count <= src.ToInt64(), "overlapping region src");
     Debug.Assert(0 <= count, "negative count");
     unsafe
     {
         var dstSpan = new System.Span <byte>(dst.ToPointer(), count);
         var srcSpan = new System.Span <byte>(src.ToPointer(), count);
         srcSpan.CopyTo(dstSpan);
     }
 }
Ejemplo n.º 3
0
 internal static bool MemoryCompare(System.IntPtr buf1, System.IntPtr buf2, int count)
 {
     Debug.Assert(buf1 != buf2, "buf1 and buf2 are the same");
     Debug.Assert(buf1.ToInt64() < buf2.ToInt64() || buf2.ToInt64() + count <= buf1.ToInt64(), "overlapping region buf1");
     Debug.Assert(buf2.ToInt64() < buf1.ToInt64() || buf1.ToInt64() + count <= buf2.ToInt64(), "overlapping region buf2");
     Debug.Assert(0 <= count, "negative count");
     unsafe
     {
         ReadOnlySpan <byte> span1 = new ReadOnlySpan <byte>(buf1.ToPointer(), count);
         ReadOnlySpan <byte> span2 = new ReadOnlySpan <byte>(buf2.ToPointer(), count);
         return(!MemoryExtensions.SequenceEqual(span1, span2));
         //0​ if all count bytes of lhs and rhs are equal.
         // TODO: confirm condition with tests
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceFailureActionsInfo"/> class.
        /// </summary>
        internal ServiceFailureActionsInfo(System.TimeSpan resetPeriod, string rebootMessage, string restartCommand
                                           , System.Collections.Generic.IReadOnlyCollection <ScAction> actions)
        {
            dwResetPeriod = resetPeriod == System.TimeSpan.MaxValue ? uint.MaxValue : (uint)System.Math.Round(resetPeriod.TotalSeconds);
            lpRebootMsg   = rebootMessage;
            lpCommand     = restartCommand;
            cActions      = actions?.Count ?? 0;

            if (null != actions)
            {
                lpsaActions = System.Runtime.InteropServices.Marshal.AllocHGlobal(
                    System.Runtime.InteropServices.Marshal.SizeOf <ScAction>() * cActions
                    );

                if (lpsaActions == System.IntPtr.Zero)
                {
                    throw new System.Exception(
                              string.Format("Unable to allocate memory for service action, error was: 0x{0:X}"
                                            , System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
                }

                System.IntPtr nextAction = lpsaActions;

                foreach (ScAction action in actions)
                {
                    System.Runtime.InteropServices.Marshal.StructureToPtr(action, nextAction, fDeleteOld: false);
                    nextAction = (System.IntPtr)(nextAction.ToInt64() + System.Runtime.InteropServices.Marshal.SizeOf <ScAction>());
                }
            }
            else
            {
                lpsaActions = System.IntPtr.Zero;
            }
        }
        // https://github.com/jpobst/Pinta/blob/master/Pinta.Core/Managers/SystemManager.cs
        public static Utsname Uname()
        {
            Utsname uts = null;

            System.IntPtr buf = System.IntPtr.Zero;

            buf = System.Runtime.InteropServices.Marshal.AllocHGlobal(8192);
            // This is a hacktastic way of getting sysname from uname ()
            if (uname_syscall(buf) == 0)
            {
                uts         = new Utsname();
                uts.SysName = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(buf);

                long bufVal = buf.ToInt64();
                uts.NodeName   = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(new System.IntPtr(bufVal + 1 * 65));
                uts.Release    = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(new System.IntPtr(bufVal + 2 * 65));
                uts.Version    = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(new System.IntPtr(bufVal + 3 * 65));
                uts.Machine    = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(new System.IntPtr(bufVal + 4 * 65));
                uts.DomainName = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(new System.IntPtr(bufVal + 5 * 65));

                if (buf != System.IntPtr.Zero)
                {
                    System.Runtime.InteropServices.Marshal.FreeHGlobal(buf);
                }
            }     // End if (uname_syscall(buf) == 0)

            return(uts);
        }     // End Function Uname
Ejemplo n.º 6
0
 internal void WriteAndPositionByRow <T>(T[] data, int offset, int count) where T : struct
 {
     Debug.Assert(count <= dataBox.RowPitch);
     Utilities.Write(dataPointer, data, offset, count);
     dataPointer += dataBox.RowPitch;
     Debug.Assert((dataPointer.ToInt64() - dataBox.DataPointer.ToInt64()) <= bufferSize);
 }
Ejemplo n.º 7
0
    protected System.IntPtr GetObjectPtr(int index)
    {
        if (index >= Capacity)
        {
            throw new System.IndexOutOfRangeException("Out of range access in " + GetType().Name);
        }

        return((System.IntPtr)(m_Buffer.ToInt64() + StructureSize * index));
    }
Ejemplo n.º 8
0
        static public System.IntPtr Ceiling(System.IntPtr value, System.UInt32 multiple)
        {
            if (multiple == 0)
            {
                return(value);
            }

            var remainder = value.ToInt64() % multiple;

            if (remainder == 0)
            {
                return(value);
            }
            else
            {
                return(new System.IntPtr(value.ToInt64() + multiple - remainder));
            }
        }
Ejemplo n.º 9
0
        } // End Function LoadSharedObject

        public static bool Unload(System.IntPtr hSO)
        {
            bool bError = true;

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

            try
            {
                if (System.Environment.OSVersion.Platform == System.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 System.ApplicationException("Error unloading handle " + hSO.ToInt64().ToString()
                                                              + System.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 (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            } // End Catch

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

            return(bError);
        } // End Function Unload
Ejemplo n.º 10
0
    private System.Collections.IEnumerator LoadFile()
    {
        ms_www = new UnityEngine.WWW(m_bankPath);

        yield return(ms_www);

        uint in_uInMemoryBankSize = 0;

        // Allocate an aligned buffer
        try
        {
            ms_pinnedArray =
                System.Runtime.InteropServices.GCHandle.Alloc(ms_www.bytes, System.Runtime.InteropServices.GCHandleType.Pinned);
            ms_pInMemoryBankPtr  = ms_pinnedArray.AddrOfPinnedObject();
            in_uInMemoryBankSize = (uint)ms_www.bytes.Length;

            // Array inside the WWW object is not aligned. Allocate a new array for which we can guarantee the alignment.
            if ((ms_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0)
            {
                var alignedBytes    = new byte[ms_www.bytes.Length + AK_BANK_PLATFORM_DATA_ALIGNMENT];
                var new_pinnedArray =
                    System.Runtime.InteropServices.GCHandle.Alloc(alignedBytes, System.Runtime.InteropServices.GCHandleType.Pinned);
                var new_pInMemoryBankPtr = new_pinnedArray.AddrOfPinnedObject();
                var alignedOffset        = 0;

                // New array is not aligned, so we will need to use an offset inside it to align our data.
                if ((new_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0)
                {
                    var alignedPtr = (new_pInMemoryBankPtr.ToInt64() + AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) &
                                     ~AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK;
                    alignedOffset        = (int)(alignedPtr - new_pInMemoryBankPtr.ToInt64());
                    new_pInMemoryBankPtr = new System.IntPtr(alignedPtr);
                }

                // Copy the bank's bytes in our new array, at the correct aligned offset.
                System.Array.Copy(ms_www.bytes, 0, alignedBytes, alignedOffset, ms_www.bytes.Length);

                ms_pInMemoryBankPtr = new_pInMemoryBankPtr;
                ms_pinnedArray.Free();
                ms_pinnedArray = new_pinnedArray;
            }
        }
        catch
        {
            yield break;
        }

        var result = AkSoundEngine.LoadBank(ms_pInMemoryBankPtr, in_uInMemoryBankSize, out ms_bankID);

        if (result != AKRESULT.AK_Success)
        {
            UnityEngine.Debug.LogError("WwiseUnity: AkMemBankLoader: bank loading failed with result " + result);
        }
    }
Ejemplo n.º 11
0
        internal static T[] MarshalUnmananagedArrayToStruct <T>(this System.IntPtr unmanagedArray, int length)
        {
            int size = System.Runtime.InteropServices.Marshal.SizeOf <T>();

            T[] mangagedArray = new T[length];

            for (int i = 0; i < length; i++)
            {
                System.IntPtr ins = new System.IntPtr(unmanagedArray.ToInt64() + i * size);
                mangagedArray[i] = System.Runtime.InteropServices.Marshal.PtrToStructure <T>(ins);
            }

            return(mangagedArray);
        }
Ejemplo n.º 12
0
        public static void WriteBytes(RGBAnimation anim, System.IntPtr ptr)
        {
            int   trackSize = Marshal.SizeOf(typeof(RGBAnimationTrack));
            short count     = (short)anim.tracks.Length;

            Marshal.WriteInt16(ptr, 0, anim.duration);
            Marshal.WriteInt16(ptr, 2, count);

            for (int i = 0; i < count; ++i)
            {
                var trackPtr = new System.IntPtr(ptr.ToInt64() + 4 + i * trackSize);
                Marshal.StructureToPtr(anim.tracks[i], trackPtr, false);
            }
        }
Ejemplo n.º 13
0
        public MMKVPMarshaller(MatchMakingKeyValuePair_t[] filters)
        {
            if (filters == null)
            {
                return;
            }

            int sizeOfMMKVP = Marshal.SizeOf(typeof(MatchMakingKeyValuePair_t));

            m_pNativeArray  = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)) * filters.Length);
            m_pArrayEntries = Marshal.AllocHGlobal(sizeOfMMKVP * filters.Length);
            for (int i = 0; i < filters.Length; ++i)
            {
                Marshal.StructureToPtr(filters[i], new IntPtr(m_pArrayEntries.ToInt64() + (i * sizeOfMMKVP)), false);
            }
            Marshal.WriteIntPtr(m_pNativeArray, m_pArrayEntries);
        }
Ejemplo n.º 14
0
        public static RGBAnimation ReadBytes(System.IntPtr ptr)
        {
            RGBAnimation ret = new RGBAnimation();

            ret.duration = Marshal.ReadInt16(ptr, 0);
            short count = Marshal.ReadInt16(ptr, 2);

            ret.tracks = new RGBAnimationTrack[count];

            int trackSize = Marshal.SizeOf(typeof(RGBAnimationTrack));

            for (int i = 0; i < count; ++i)
            {
                var trackPtr = new System.IntPtr(ptr.ToInt64() + 4 + i * trackSize);
                ret.tracks[i] = (RGBAnimationTrack)Marshal.PtrToStructure(trackPtr, typeof(RGBAnimationTrack));
            }

            return(ret);
        }
Ejemplo n.º 15
0
    private uint AllocateAlignedBuffer(byte[] data)
    {
        uint uInMemoryBankSize = 0;

        // Allocate an aligned buffer
        try
        {
            ms_pinnedArray =
                System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned);
            ms_pInMemoryBankPtr = ms_pinnedArray.AddrOfPinnedObject();
            uInMemoryBankSize   = (uint)data.Length;

            // Array inside the WWW object is not aligned. Allocate a new array for which we can guarantee the alignment.
            if ((ms_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0)
            {
                var alignedBytes    = new byte[data.Length + AK_BANK_PLATFORM_DATA_ALIGNMENT];
                var new_pinnedArray =
                    System.Runtime.InteropServices.GCHandle.Alloc(alignedBytes, System.Runtime.InteropServices.GCHandleType.Pinned);
                var new_pInMemoryBankPtr = new_pinnedArray.AddrOfPinnedObject();
                var alignedOffset        = 0;

                // New array is not aligned, so we will need to use an offset inside it to align our data.
                if ((new_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0)
                {
                    var alignedPtr = (new_pInMemoryBankPtr.ToInt64() + AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) &
                                     ~AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK;
                    alignedOffset        = (int)(alignedPtr - new_pInMemoryBankPtr.ToInt64());
                    new_pInMemoryBankPtr = new System.IntPtr(alignedPtr);
                }

                // Copy the bank's bytes in our new array, at the correct aligned offset.
                System.Array.Copy(data, 0, alignedBytes, alignedOffset, data.Length);

                ms_pInMemoryBankPtr = new_pInMemoryBankPtr;
                ms_pinnedArray.Free();
                ms_pinnedArray = new_pinnedArray;
            }
        }
        catch
        {
        }
        return(uInMemoryBankSize);
    }
Ejemplo n.º 16
0
    public void Add(UnityEngine.Vector3 in_Pos, UnityEngine.Vector3 in_Forward, UnityEngine.Vector3 in_Top,
                    uint in_ChannelMask)
    {
        if (Count >= m_MaxCount)
        {
            throw new System.IndexOutOfRangeException("Out of range access in AkChannelEmitterArray");
        }

        //Marshal doesn't do floats.  So copy the bytes themselves.  Grrr.
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Forward.x), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Forward.y), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Forward.z), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Top.x), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Top.y), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Top.z), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Pos.x), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Pos.y), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current,
                                                          System.BitConverter.ToInt32(System.BitConverter.GetBytes(in_Pos.z), 0));
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(float));
        System.Runtime.InteropServices.Marshal.WriteInt32(m_Current, (int)in_ChannelMask);
        m_Current = (System.IntPtr)(m_Current.ToInt64() + sizeof(uint));

        Count++;
    }
        System.IntPtr System.Runtime.InteropServices.ICustomMarshaler.MarshalManagedToNative(object objManagedObj)
        {
            string managedObj = objManagedObj as string;

            if (managedObj == null)
                return System.IntPtr.Zero;

            // not null terminated
            byte[] strbuf = System.Text.Encoding.UTF8.GetBytes(managedObj);
            System.IntPtr buffer = System.Runtime.InteropServices.Marshal.AllocHGlobal(strbuf.Length + 1);
            System.Runtime.InteropServices.Marshal.Copy(strbuf, 0, buffer, strbuf.Length);

            // write the terminating null
            //Marshal.WriteByte(buffer + strbuf.Length, 0);

            long lngPosEnd = buffer.ToInt64() + strbuf.Length;
            System.IntPtr ptrPosEnd = new System.IntPtr(lngPosEnd);
            System.Runtime.InteropServices.Marshal.WriteByte(ptrPosEnd, 0);

            return buffer;
        }
Ejemplo n.º 18
0
        public override IEnumerable <CommandDTOBase?> Execute(string[] args)
        {
            // lists named pipes
            // reference - https://stackoverflow.com/questions/25109491/how-can-i-get-a-list-of-all-open-named-pipes-in-windows-and-avoiding-possible-ex/25126943#25126943
            var             namedPipes = new List <string>();
            WIN32_FIND_DATA lpFindFileData;

            var ptr = FindFirstFile(@"\\.\pipe\*", out lpFindFileData);

            namedPipes.Add(lpFindFileData.cFileName);
            while (FindNextFile(ptr, out lpFindFileData))
            {
                namedPipes.Add(lpFindFileData.cFileName);
            }
            FindClose(ptr);

            namedPipes.Sort();

            foreach (var namedPipe in namedPipes)
            {
                FileSecurity  security;
                var           sddl          = "";
                int           iProcessId    = 0;
                string        svProcessName = "";
                System.IntPtr hPipe         = System.IntPtr.Zero;
                bool          bvRet         = false;

                // Try to identify ProcessID and ProcessName
                try
                {
                    //Get a handle to the pipe
                    hPipe = CreateFile(
                        System.String.Format("\\\\.\\pipe\\{0}", namedPipe), // The name of the file or device to be created or opened.
                        FileAccess.Read,                                     // The requested access to the file or device.
                        FileShare.None,                                      // The requested sharing mode of the file or device.
                        System.IntPtr.Zero,                                  // Optional. A pointer to a SECURITY_ATTRIBUTES structure.
                        FileMode.Open,                                       // An action to take on a file or device that exists or does not exist.
                        FileAttributes.Normal,                               // The file or device attributes and flags.
                        System.IntPtr.Zero);                                 // Optional. A valid handle to a template file with the GENERIC_READ access right.


                    if (hPipe.ToInt64() != -1) //verify CreateFile did not return "INVALID_HANDLE_VALUE"
                    {
                        //Retrieve the ProcessID registered for the pipe.
                        bvRet = GetNamedPipeServerProcessId(
                            hPipe,           // A handle to an instance of a named pipe.
                            out iProcessId); // The process identifier.

                        //If GetNamedPipeServerProcessId was successful, get the process name for the returned ProcessID
                        if (bvRet)
                        {
                            svProcessName = System.Diagnostics.Process.GetProcessById(iProcessId).ProcessName;
                        }
                        else
                        {
                            //GetNamedPipeServerProcessId was unsuccessful
                            svProcessName = "Unk";
                        }

                        //Close the pipe handle
                        CloseHandle(hPipe);
                    }
                    else
                    {
                        //CreateFile returned "INVALID_HANDLE_VALUE" or 0xffffffff.
                        svProcessName = "Unk";
                    }
                }
                catch
                {
                    //Catch the exception. ProcessName is set to Unk.
                    svProcessName = "Unk";
                }

                try
                {
                    security = File.GetAccessControl(System.String.Format("\\\\.\\pipe\\{0}", namedPipe));
                    sddl     = security.GetSecurityDescriptorSddlForm(AccessControlSections.All);
                }
                catch
                {
                    sddl = "ERROR";
                }

                if (!System.String.IsNullOrEmpty(sddl) && !sddl.Equals("ERROR"))
                {
                    yield return(new NamedPipesDTO()
                    {
                        Name = namedPipe,
                        Sddl = sddl,
                        //SecurityDescriptor = new RawSecurityDescriptor(sddl)

                        OwningProcessName = svProcessName,
                        OwningProcessPID = iProcessId
                    });
                }
                else
                {
                    yield return(new NamedPipesDTO()
                    {
                        Name = namedPipe,
                        Sddl = sddl,
                        //SecurityDescriptor = null

                        OwningProcessName = svProcessName,
                        OwningProcessPID = iProcessId
                    });
                }
            }
        }
Ejemplo n.º 19
0
        IEnumerator RecordCR()
        {
            int recRate = 0;
            int namelen = 255;

            System.Text.StringBuilder name = new System.Text.StringBuilder(namelen);
            System.Guid       guid;
            FMOD.SPEAKERMODE  speakermode;
            FMOD.DRIVER_STATE driverstate;
            result = system.getRecordDriverInfo(this.recordDeviceId, name, namelen, out guid, out recRate, out speakermode, out recChannels, out driverstate);
            ERRCHECK(result, "system.getRecordDriverInfo");

            // compensate the input rate for the current output rate
            this.GetComponent <AudioSource>().pitch = ((float)(recRate * recChannels) / (float)(AudioSettings.outputSampleRate * (int)AudioSettings.speakerMode));

            exinfo                  = new FMOD.CREATESOUNDEXINFO();
            exinfo.numchannels      = recChannels;
            exinfo.format           = FMOD.SOUND_FORMAT.PCM16;
            exinfo.defaultfrequency = recRate;
            exinfo.length           = (uint)(recRate * sizeof(short) * recChannels);

            result = system.createSound(string.Empty, FMOD.MODE.LOOP_NORMAL | FMOD.MODE.OPENUSER, ref exinfo, out sound);
            ERRCHECK(result, "system.createSound");

            this.GetComponent <AudioSource>().Play();

            result = system.recordStart(this.recordDeviceId, sound, true);
            ERRCHECK(result, "system.recordStart");

            result = sound.getLength(out soundlength, FMOD.TIMEUNIT.PCM);
            ERRCHECK(result, "sound.getLength");

            this.isRecording = true;

            if (this.OnRecordingStarted != null)
            {
                this.OnRecordingStarted.Invoke(this.gameObjectName);
            }

            for (;;)
            {
                result = system.update();
                ERRCHECK(result, "system.update", false);

                if (this.isPaused)
                {
                    yield return(null);
                }

                uint recordpos = 0;

                system.getRecordPosition(this.recordDeviceId, out recordpos);
                ERRCHECK(result, "system.getRecordPosition");

                if (recordpos != lastrecordpos)
                {
                    int blocklength;

                    blocklength = (int)recordpos - (int)lastrecordpos;
                    if (blocklength < 0)
                    {
                        blocklength += (int)soundlength;
                    }

                    /*
                     * Lock the sound to get access to the raw data.
                     */
                    result = sound.@lock((uint)(lastrecordpos * exinfo.numchannels * 2), (uint)(blocklength * exinfo.numchannels * 2), out ptr1, out ptr2, out len1, out len2);   /* * exinfo.numchannels * 2 = stereo 16bit.  1 sample = 4 bytes. */

                    /*
                     * Write it to output.
                     */
                    if (ptr1.ToInt64() != 0 && len1 > 0)
                    {
                        datalength += len1;
                        byte[] barr = new byte[len1];
                        Marshal.Copy(ptr1, barr, 0, (int)len1);

                        this.AddBytesToOutputBuffer(barr);
                    }
                    if (ptr2.ToInt64() != 0 && len2 > 0)
                    {
                        datalength += len2;
                        byte[] barr = new byte[len2];
                        Marshal.Copy(ptr2, barr, 0, (int)len2);
                        this.AddBytesToOutputBuffer(barr);
                    }

                    /*
                     * Unlock the sound to allow FMOD to use it again.
                     */
                    result = sound.unlock(ptr1, ptr2, len1, len2);
                }

                lastrecordpos = recordpos;

                // print(string.Format("Record buffer pos = {0} : Record time = {1}:{2}", recordpos, datalength / exinfo.defaultfrequency / exinfo.numchannels / 2 / 60, (datalength / exinfo.defaultfrequency / exinfo.numchannels / 2) % 60));

                // System.Threading.Thread.Sleep(10);

                yield return(null);
            }
        }
Ejemplo n.º 20
0
 public static System.IntPtr AddToIntPtr(System.IntPtr ptr, int offset)
 {
     // cannot use System.IntPtr.Add as that was introduced in .NET Framework 4
     // Unity only comes in 64-bit flavours, so this should be fine
     return(new System.IntPtr(ptr.ToInt64() + offset));
 }
Ejemplo n.º 21
0
        public System.IntPtr Allocate(long size)
        {
            System.Collections.Generic.LinkedList <T> candidates = new System.Collections.Generic.LinkedList <T>();

            System.IntPtr pointer = System.IntPtr.Zero;

            bool continue_ = true;

            size += System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)) % System.IntPtr.Size;

            int wide = System.IntPtr.Size * 8; // 32 or 64

            while (continue_)
            {
                //If there is no size make a new object which allocated 12 or more bytes to make a gap, next allocation should be aligned.
                if (size == 0)
                {
                    object gap = new object();
                }

                candidates.AddLast(new T());

                #region Unused

                //Crashed compiler... Base method is not marked unsafe?

                //unsafe{

                ////Make a local reference to the result
                //System.TypedReference trResult = __makeref(candidates.Last.Value);

                ////Make a pointer to the local reference
                //System.IntPtr localReferenceResult = *(System.IntPtr*)(&trResult);

                //}

                #endregion

                pointer = Concepts.Classes.CommonIntermediateLanguage.As <T, System.IntPtr>(candidates.Last.Value);

                #region Unused

                //Fix the handle
                //System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(candidates.Last.Value, System.Runtime.InteropServices.GCHandleType.Pinned);

                //To determine if its sized correctly.
                //pointer = handle.AddrOfPinnedObject();

                #endregion

                continue_ = (pointer.ToInt64() & System.IntPtr.Size - 1) != 0 || (pointer.ToInt64() % wide) == 24;

                #region Unused

                //handle.Free();

                #endregion
            }

            return(pointer);
        }
Ejemplo n.º 22
0
 private System.IntPtr GetObjectPtr(int index)
 {
     return((System.IntPtr)(m_Buffer.ToInt64() + SIZE_OF_AKAUXSENDVALUE * index));
 }
Ejemplo n.º 23
0
 private System.IntPtr GetObjectPtr(int index)
 {
     return((System.IntPtr)(m_Buffer.ToInt64() + SIZE_OF_STRUCTURE * index));
 }
Ejemplo n.º 24
0
 internal void ReadAndPosition <T>(ref T data) where T : struct
 {
     m_dataPointer = Utilities.ReadAndPosition(m_dataPointer, ref data);
     Debug.Assert((m_dataPointer.ToInt64() - m_dataBox.DataPointer.ToInt64()) <= m_bufferSize);
 }
Ejemplo n.º 25
0
 private System.IntPtr GetObjectPtr(int index)
 {
     return((System.IntPtr)(m_Buffer.ToInt64() + SIZE_OF_AKTRIANGLE * index));
 }
Ejemplo n.º 26
0
        private System.IntPtr ConvertGameObjectToCapturyActor(GameObject g)
        {
            CapturyActor actor = new CapturyActor();

            Transform[] trafos = g.GetComponentsInChildren <Transform>();
            //Debug.Log("have " + (trafos.Length - 1) + " children");
            actor.name      = System.Text.Encoding.ASCII.GetBytes(g.name);
            actor.id        = 17;
            actor.numJoints = trafos.Length - 1;

            System.IntPtr mem = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CapturyActor)) + actor.numJoints * Marshal.SizeOf(typeof(CapturyJoint)));
            actor.joints = new System.IntPtr(mem.ToInt64() + Marshal.SizeOf(typeof(CapturyActor)));

            actor.numBlobs = 0;
            actor.blobs    = System.IntPtr.Zero;

            Marshal.StructureToPtr(actor, mem, false);

            CapturyJoint[] joints               = new CapturyJoint[trafos.Length - 1];
            Vector3[]      globalPositions      = new Vector3[trafos.Length - 1];
            Vector3[]      globalPositionsUnity = new Vector3[trafos.Length - 1];
            Vector3[]      trafoPos             = new Vector3[trafos.Length];

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

            names[trafos[0].name] = -1; // this is the overall parent

            System.IntPtr j = actor.joints;
            for (int i = 0; i < actor.numJoints; ++i)
            {
                names[trafos[i + 1].name] = i;
                joints[i].parent          = names[trafos[i + 1].parent.name];

                joints[i].name = System.Text.Encoding.ASCII.GetBytes(trafos[i + 1].name);
                Vector3 pos;
                int     parent = joints[i].parent;
                if (parent != -1)
                {
                    pos = networkPlugin.ConvertPositionToLive(trafos[i + 1].position - trafos[i + 1].parent.position);
                }
                else
                {
                    pos = networkPlugin.ConvertPositionToLive(trafos[i + 1].position);
                }
                joints[i].ox = pos.x;
                joints[i].oy = pos.y;
                joints[i].oz = pos.z;

                Quaternion delta     = trafos[i + 1].rotation;
                Quaternion liveDelta = networkPlugin.ConvertRotationToLive(delta);
                Vector3    rot       = networkPlugin.ConvertToEulerAngles(liveDelta);
                joints[i].rx = 0.0f; // rot.x;
                joints[i].ry = 0.0f; // rot.y;
                joints[i].rz = 0.0f; // rot.z;

                trafoPos[i] = trafos[i + 1].position;

                globalPositions[i] = new Vector3(joints[i].ox, joints[i].oy, joints[i].oz);
                int p = joints[i].parent;
                if (p > -1)
                {
                    globalPositions[i] += globalPositions[p];
                }
                globalPositionsUnity[i] = networkPlugin.ConvertPosition(globalPositions[i]) - trafoPos[i];

                Marshal.StructureToPtr(joints[i], j, false);
                j = new System.IntPtr(j.ToInt64() + Marshal.SizeOf(typeof(CapturyJoint)));
            }

            return(mem);
        }
Ejemplo n.º 27
0
 internal void WriteAndPosition <T>(T[] data, int offset, int count) where T : struct
 {
     dataPointer = Utilities.Write(dataPointer, data, offset, count);
     Debug.Assert((dataPointer.ToInt64() - dataBox.DataPointer.ToInt64()) <= bufferSize);
 }
Ejemplo n.º 28
0
 internal void WriteAndPosition <T>(ref T data) where T : struct
 {
     dataPointer = Utilities.WriteAndPosition(dataPointer, ref data);
     Debug.Assert((dataPointer.ToInt64() - dataBox.DataPointer.ToInt64()) <= bufferSize);
 }
Ejemplo n.º 29
0
        static public System.Boolean MatchPattern(System.IntPtr address, System.Byte?[] pattern)
        {
            var equals = Memory.Equals <System.Byte>(address, pattern);

            if (!equals)
            {
                Log.Information($"{nameof(AddressLibrary)}: Unexpected {nameof(pattern)} encountered at {Main.MainModuleName} + {address.ToInt64() - Main.MainModule.BaseAddress.ToInt64():X}, {System.Convert.ToHexString(Memory.ReadArray<System.Byte>(address, pattern.Length))}.");
            }

            return(equals);
        }