System.Runtime.InteropServices.Marshal.PtrToStringAnsi(System.IntPtr)

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

629 Examples 7

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

public string GetStringValue()
        {
            return Marshal.PtrToStringAnsi(this.value) ?? string.Empty;
        }

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

private string GetErrorMessage()
        {
            return Marshal.PtrToStringAnsi(this.message) ?? Properties.Resources.UnspecifiedError;
        }

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

public string GetStringValue()
        {
            return Marshal.PtrToStringAnsi(this.value);
        }

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

public unsafe ReadOnlyCollection<string> ToReadOnlyCollection()
        {
            var items = new List<string>();

            if (this.arrayPointer != IntPtr.Zero)
            {
                var stringMemoryAdddress = (IntPtr*)this.arrayPointer;

                while (*stringMemoryAdddress != IntPtr.Zero)
                {
                    items.Add(Marshal.PtrToStringAnsi(*stringMemoryAdddress));

                    stringMemoryAdddress++;
                }
            }

            return items.AsReadOnly();
        }

19 View Source File : DynamicInvoke.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName)
        {
            IntPtr FunctionPtr = IntPtr.Zero;
            try
            {
                Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));
                Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));
                Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;
                Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);
                Int64 pExport = 0;
                if (Magic == 0x010b)
                {
                    pExport = OptHeader + 0x60;
                }
                else
                {
                    pExport = OptHeader + 0x70;
                }
                Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);
                Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));
                Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));
                Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));
                Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));
                Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));
                Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));
                for (int i = 0; i < NumberOfNames; i++)
                {
                    string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
                    if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase))
                    {
                        Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
                        Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
                        FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
                        break;
                    }
                }
            }
            catch
            {
                throw new InvalidOperationException("Failed to parse module exports.");
            }

            if (FunctionPtr == IntPtr.Zero)
            {
                throw new MissingMethodException(ExportName + ", export function not found.");
            }
            return FunctionPtr;
        }

19 View Source File : OvrWrap64.Common.cs
License : MIT License
Project Creator : ab4d

public override string GetString(IntPtr sessionPtr, string propertyName, string defaultValue)
        {
            IntPtr resultPtr = SafeNativeMethods.ovr_GetString(sessionPtr, propertyName, defaultValue);
            string result = Marshal.PtrToStringAnsi(resultPtr);

            return result;
        }

19 View Source File : OvrWrap64.Common.cs
License : MIT License
Project Creator : ab4d

public override string GetVersionString()
        {
            IntPtr stringPtr = SafeNativeMethods.ovr_GetVersionString();
            string resultString = Marshal.PtrToStringAnsi(stringPtr);
            return resultString;
        }

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

private void LoadBlendShapes(IntPtr replacedet, long vertexCount)
    {
        UInt32 blendShapeCount = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeCount(replacedet);
        IntPtr blendShapeVerts = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeVertices(replacedet);

        AvatarLogger.Log("LoadBlendShapes: " + blendShapeCount);

        if (blendShapeVerts != IntPtr.Zero)
        {
            long offset = 0;
            long blendVertexSize = (long)Marshal.SizeOf(typeof(ovrAvatarBlendVertex));
            long blendVertexBufferStart = blendShapeVerts.ToInt64();

            for (UInt32 blendIndex = 0; blendIndex < blendShapeCount; blendIndex++)
            {
                Vector3[] blendVerts = new Vector3[vertexCount];
                Vector3[] blendNormals = new Vector3[vertexCount];
                Vector3[] blendTangents = new Vector3[vertexCount];

                for (long i = 0; i < vertexCount; i++)
                {
                    ovrAvatarBlendVertex vertex = (ovrAvatarBlendVertex)Marshal.PtrToStructure(new IntPtr(blendVertexBufferStart + offset), typeof(ovrAvatarBlendVertex));
                    blendVerts[i] = new Vector3(vertex.x, vertex.y, -vertex.z);
                    blendNormals[i] = new Vector3(vertex.nx, vertex.ny, -vertex.nz);
                    blendTangents[i] = new Vector4(vertex.tx, vertex.ty, -vertex.tz);

                    offset += blendVertexSize;
                }

                IntPtr namePtr = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeName(replacedet, blendIndex);
                string name = Marshal.PtrToStringAnsi(namePtr);
                const float frameWeight = 100f;
                mesh.AddBlendShapeFrame(name, frameWeight, blendVerts, blendNormals, blendTangents);
            }
        }
    }

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

void CPPLogCallback(IntPtr tag, IntPtr message)
    {
      Debug.Log(string.Format("{0}: {1}", Marshal.PtrToStringAnsi(tag), Marshal.PtrToStringAnsi(message)));
    }

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

public string GetOption(string property, out ZError error)
        {
            error = ZError.None;

            string result = null;
            using (var propertyPtr = DispoIntPtr.AllocString(property))
            {
                IntPtr resultPtr;
                if (IntPtr.Zero == (resultPtr = zmq.msg_gets(framePtr, propertyPtr)))
                {
                    error = ZError.GetLastErr();
                    return null;
                }
                else
                {
                    Marshal.FreeHGlobal(resultPtr);
                    result = Marshal.PtrToStringAnsi(resultPtr);
                }
            }
            return result;
        }

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

public static Exception GetLastLibraryError()
			{
				IntPtr text = dlerror();
				string strg = null;
				if (text != IntPtr.Zero)
				{
					strg = Marshal.PtrToStringAnsi(text);
				}
				return new DllNotFoundException(strg);
			}

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

private static bool SafeMarshalString(IntPtr cstring_ptr, out string stringContent)
        {

            stringContent = null;
            if (IsNull(cstring_ptr))
                return false;

            stringContent = Marshal.PtrToStringAnsi(cstring_ptr);
            if (string.IsNullOrEmpty(stringContent))
                return false;

            return true;
        }

19 View Source File : MidiJackWindow.cs
License : MIT License
Project Creator : aksyr

static string GetEndpointName(uint id) {
            return Marshal.PtrToStringAnsi(MidiJackGetEndpointName(id));
        }

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

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

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

            return _utf8.GetString(data);
        }

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

private static void connection_status_callback_impl(
            QuikResult nConnectionEvent,
            int nExtendedErrorCode,
            IntPtr lpcstrInfoMessage)
        {
            if (connection_status_callback != null)
            {
                connection_status_callback(
                    nConnectionEvent,
                    nExtendedErrorCode,
                    Marshal.PtrToStringAnsi(lpcstrInfoMessage));
            }
        }

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

private static void order_status_callback_impl(
            int nMode,
            int dwTransID,
            ulong d,
            IntPtr ClreplacedCode,
            IntPtr SecCode,
            double dPrice,
            int nBalance,
            double dValue,
            int nIsSell,
            int nStatus,
            IntPtr i)
        {
            if (order_status_callback != null)
            {
                order_status_callback(
                    nMode,
                    dwTransID,
                    d,
                    Marshal.PtrToStringAnsi(ClreplacedCode),
                    Marshal.PtrToStringAnsi(SecCode),
                    dPrice,
                    nBalance,
                    dValue,
                    nIsSell,
                    nStatus,
                    i);
            }
        }

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

public static string GetTradeAccount(Int32 descriptor)
        {
            return Marshal.PtrToStringAnsi(TRADE_ACCOUNT(descriptor));
        }

19 View Source File : MediaInfo.cs
License : MIT License
Project Creator : Alkl58

public String Inform()
        {
            if (MustUseAnsi)
                return Marshal.PtrToStringAnsi(MediaInfoA_Inform(Handle, (IntPtr)0));
            else
                return Marshal.PtrToStringUni(MediaInfo_Inform(Handle, (IntPtr)0));
        }

19 View Source File : MediaInfo.cs
License : MIT License
Project Creator : Alkl58

public String Get(StreamKind StreamKind, int StreamNumber, String Parameter, InfoKind KindOfInfo, InfoKind KindOfSearch)
        {
            if (MustUseAnsi)
            {
                IntPtr Parameter_Ptr = Marshal.StringToHGlobalAnsi(Parameter);
                String ToReturn = Marshal.PtrToStringAnsi(MediaInfoA_Get(Handle, (IntPtr)StreamKind, (IntPtr)StreamNumber, Parameter_Ptr, (IntPtr)KindOfInfo, (IntPtr)KindOfSearch));
                Marshal.FreeHGlobal(Parameter_Ptr);
                return ToReturn;
            }
            else
                return Marshal.PtrToStringUni(MediaInfo_Get(Handle, (IntPtr)StreamKind, (IntPtr)StreamNumber, Parameter, (IntPtr)KindOfInfo, (IntPtr)KindOfSearch));
        }

19 View Source File : MediaInfo.cs
License : MIT License
Project Creator : Alkl58

public String Get(StreamKind StreamKind, int StreamNumber, int Parameter, InfoKind KindOfInfo)
        {
            if (MustUseAnsi)
                return Marshal.PtrToStringAnsi(MediaInfoA_GetI(Handle, (IntPtr)StreamKind, (IntPtr)StreamNumber, (IntPtr)Parameter, (IntPtr)KindOfInfo));
            else
                return Marshal.PtrToStringUni(MediaInfo_GetI(Handle, (IntPtr)StreamKind, (IntPtr)StreamNumber, (IntPtr)Parameter, (IntPtr)KindOfInfo));
        }

19 View Source File : MediaInfo.cs
License : MIT License
Project Creator : Alkl58

public String Option(String Option, String Value)
        {
            if (MustUseAnsi)
            {
                IntPtr Option_Ptr = Marshal.StringToHGlobalAnsi(Option);
                IntPtr Value_Ptr = Marshal.StringToHGlobalAnsi(Value);
                String ToReturn = Marshal.PtrToStringAnsi(MediaInfoA_Option(Handle, Option_Ptr, Value_Ptr));
                Marshal.FreeHGlobal(Option_Ptr);
                Marshal.FreeHGlobal(Value_Ptr);
                return ToReturn;
            }
            else
                return Marshal.PtrToStringUni(MediaInfo_Option(Handle, Option, Value));
        }

19 View Source File : JemApi.cs
License : MIT License
Project Creator : allisterb

public static string GetMallCtlStr(string name)
        {
            void* p = stackalloc IntPtr[1];
            IntPtr retp = new IntPtr(p);
            ulong size = (ulong)sizeof(IntPtr);
            int ret = Mallctl(name, (IntPtr) p, ref size, IntPtr.Zero, 0);
            if ((ERRNO)ret == ERRNO.ENONE)
            {
                return Marshal.PtrToStringAnsi(*(IntPtr*)p);
            }
            else
            {
               throw GetExceptionForErrNo($"Could not get mallctl value {name}.", (ERRNO)ret);
            }
        }

19 View Source File : ShaderCompiler.cs
License : MIT License
Project Creator : amerkoleci

public static unsafe string? GetStringFromBlob(D3DCompiler.IDxcBlob blob)
        {
            return Marshal.PtrToStringAnsi((IntPtr)blob.GetBufferPointer());
        }

19 View Source File : IncludeShadow.cs
License : MIT License
Project Creator : amerkoleci

private static Result OpenImpl(IntPtr thisPtr, IncludeType includeType, IntPtr fileNameRef, IntPtr pParentData, ref IntPtr dataRef, ref int bytesRef)
            {
                try
                {
                    IncludeShadow shadow = ToShadow<IncludeShadow>(thisPtr);
                    Include callback = (Include)shadow.Callback;

                    Stream? stream = null;
                    Stream? parentStream = null;

                    if (shadow._frames.ContainsKey(pParentData))
                    {
                        parentStream = shadow._frames[pParentData].Stream;
                    }

                    stream = callback.Open(includeType, Marshal.PtrToStringAnsi(fileNameRef), parentStream);
                    if (stream == null)
                        return Result.Fail;

                    GCHandle handle;

                    //if (stream is DataStream)
                    //{
                    //    // Magic shortcut if we happen to get a DataStream
                    //    var data = (DataStream)stream;
                    //    dataRef = data.PositionPointer;
                    //    bytesRef = (int)(data.Length - data.Position);
                    //    handle = new GCHandle();
                    //}
                    //else
                    {
                        // Read the stream into a byte array and pin it
                        byte[] data = ReadStream(stream);
                        handle = GCHandle.Alloc(data, GCHandleType.Pinned);
                        dataRef = handle.AddrOfPinnedObject();
                        bytesRef = data.Length;
                    }

                    shadow._frames.Add(dataRef, new Frame(stream, handle));

                    return Result.Ok;
                }
                catch (SharpGenException exception)
                {
                    return exception.ResultCode.Code;
                }
                catch (Exception)
                {
                    return Result.Fail;
                }
            }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Andy53

public static string MarshalToString(this IntPtr intPtr)
        {
            if (intPtr == IntPtr.Zero)
                return "";
            return Marshal.PtrToStringAnsi(intPtr);
        }

19 View Source File : Win32Errors.cs
License : MIT License
Project Creator : Andy53

public static string GetLastWin32Error(int errorCode = 0)
        {
            if (errorCode == 0)
            {
                errorCode = Marshal.GetLastWin32Error();
            }

            try
            {
                IntPtr lpMsgBuf = IntPtr.Zero;

                int dwChars = FormatMessage(
                    FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER | FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM | FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS,
                    IntPtr.Zero,
                    (uint)errorCode,
                    0, // Default language
                    ref lpMsgBuf,
                    0,
                    IntPtr.Zero);
                if (dwChars == 0)
                {
                    // Handle the error.
                    int le = Marshal.GetLastWin32Error();
                    return "Unable to get error code string from System - Error " + le.ToString();
                }

                string sRet = Marshal.PtrToStringAnsi(lpMsgBuf);

                // Free the buffer.
                lpMsgBuf = LocalFree(lpMsgBuf);
                return sRet;
            }
            catch (Exception e)
            {
                return "Unable to get error code string from System -> " + e.ToString();
            }
        }

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

public static unsafe Memory<byte> FilterFunc(H5FilterFlags flags, uint[] parameters, Memory<byte> buffer)
        {
            // adapted from https://github.com/Blosc/hdf5-blosc/blob/bd8ee59708f366ac561153858735165d3a543b18/src/blosc_filter.c#L145-L272
            int status = 0;
            uint clevel = 5;
            uint doshuffle = 1;
            byte[] resultBuffer = null;

            CompressorCodes compcode;

            /* Filter params that are always set */
            var typesize = parameters[2];                   /* The datatype size */
            ulong outbuf_size = parameters[3];              /* Precomputed buffer guess */

            /* Optional params */
            if (parameters.Length >= 5)
                clevel = parameters[4];                     /* The compression level */

            if (parameters.Length >= 6)
                doshuffle = parameters[5];                  /* BLOSC_SHUFFLE, BLOSC_BITSHUFFLE */

            if (parameters.Length >= 7)
            {
                compcode = (CompressorCodes)parameters[6];  /* The Blosc compressor used */

                /* Check that we actually have support for the compressor code */
                var namePtr = IntPtr.Zero;
                var compressorsPtr = Blosc.blosc_list_compressors();
                var code = Blosc.blosc_compcode_to_compname(compcode, ref namePtr);

                if (code == -1)
                    throw new Exception($"This Blosc library does not have support for the '{Marshal.PtrToStringAnsi(namePtr)}' compressor, but only for: {Marshal.PtrToStringAnsi(compressorsPtr)}.");
            }

            /* We're decompressing */
            if (flags.HasFlag(H5FilterFlags.Decompress))
            {
                /* Extract the exact outbuf_size from the buffer header.
                *
                * NOTE: the guess value got from "cd_values" corresponds to the
                * uncompressed chunk size but it should not be used in a general
                * cases since other filters in the pipeline can modify the buffere
                *  size.
                */

                fixed (byte* srcPtr = buffer.Span)
                {
                    Blosc.blosc_cbuffer_sizes(new IntPtr(srcPtr), out outbuf_size, out var cbytes, out var blocksize);

                    resultBuffer = new byte[outbuf_size];

                    fixed (byte* destPtr = resultBuffer)
                    {
                        status = Blosc.blosc_decompress(new IntPtr(srcPtr), new IntPtr(destPtr), outbuf_size);

                        /* decompression failed */
                        if (status <= 0)
                            throw new Exception("Blosc decompression error.");
                    }
                }

                return resultBuffer;
            }

            /* We're compressing */
            else
            {
                throw new Exception("Writing data chunks is not yet supported by HDF5.NET.");
            }
        }

19 View Source File : DLLFromMemory.cs
License : MIT License
Project Creator : arsium

IntPtr GetPtrFromFuncName(string funcName)
    {
        if (Disposed)                       throw new ObjectDisposedException("DLLFromMemory");
        if (string.IsNullOrEmpty(funcName)) throw new ArgumentException("funcName");
        if (!IsDll)                         throw new InvalidOperationException("Loaded Module is not a DLL");
        if (!_initialized)                  throw new InvalidOperationException("Dll is not initialized");

        IntPtr pDirectory = PtrAdd(pNTHeaders, Of.IMAGE_NT_HEADERS_OptionalHeader + (Is64BitProcess ? Of64.IMAGE_OPTIONAL_HEADER_ExportTable: Of32.IMAGE_OPTIONAL_HEADER_ExportTable));
        IMAGE_DATA_DIRECTORY Directory = PtrRead<IMAGE_DATA_DIRECTORY>(pDirectory);
        if (Directory.Size == 0) throw new DllException("Dll has no export table");

        IntPtr pExports = PtrAdd(pCode, Directory.VirtualAddress);
        IMAGE_EXPORT_DIRECTORY Exports = PtrRead<IMAGE_EXPORT_DIRECTORY>(pExports);
        if (Exports.NumberOfFunctions == 0 || Exports.NumberOfNames == 0) throw new DllException("Dll exports no functions");

        IntPtr pNameRef = PtrAdd(pCode, Exports.AddressOfNames);
        IntPtr pOrdinal = PtrAdd(pCode, Exports.AddressOfNameOrdinals);
        for (int i = 0; i < Exports.NumberOfNames; i++, pNameRef = PtrAdd(pNameRef, sizeof(uint)), pOrdinal = PtrAdd(pOrdinal, sizeof(ushort)))
        {
            uint NameRef = PtrRead<uint>(pNameRef);
            ushort Ordinal = PtrRead<ushort>(pOrdinal);
            string curFuncName = Marshal.PtrToStringAnsi(PtrAdd(pCode, NameRef));
            if (curFuncName == funcName)
            {
                if (Ordinal > Exports.NumberOfFunctions) throw new DllException("Invalid function ordinal");
                IntPtr pAddressOfFunction = PtrAdd(pCode, (Exports.AddressOfFunctions + (uint)(Ordinal * 4)));
                return PtrAdd(pCode, PtrRead<uint>(pAddressOfFunction));
            }
        }
            
        throw new DllException("Dll exports no function named " + funcName);
    }

19 View Source File : DLLFromMemory.cs
License : MIT License
Project Creator : arsium

static IntPtr[] BuildImportTable(ref IMAGE_NT_HEADERS OrgNTHeaders, IntPtr pCode)
    {
        System.Collections.Generic.List<IntPtr> ImportModules = new System.Collections.Generic.List<IntPtr>();
        uint NumEntries = OrgNTHeaders.OptionalHeader.ImportTable.Size / Sz.IMAGE_IMPORT_DESCRIPTOR;
        IntPtr pImportDesc = PtrAdd(pCode, OrgNTHeaders.OptionalHeader.ImportTable.VirtualAddress);
        for (uint i = 0; i != NumEntries; i++, pImportDesc = PtrAdd(pImportDesc, Sz.IMAGE_IMPORT_DESCRIPTOR))
        {
            IMAGE_IMPORT_DESCRIPTOR ImportDesc = PtrRead<IMAGE_IMPORT_DESCRIPTOR>(pImportDesc);
            if (ImportDesc.Name == 0) break;

            IntPtr handle = Win.LoadLibrary(PtrAdd(pCode, ImportDesc.Name));
            if (PtrIsInvalidHandle(handle))
            {
                foreach (IntPtr m in ImportModules) Win.FreeLibrary(m);
                ImportModules.Clear();
                throw new DllException("Can't load libary " + Marshal.PtrToStringAnsi(PtrAdd(pCode, ImportDesc.Name)));
            }
            ImportModules.Add(handle);

            IntPtr pThunkRef, pFuncRef;
            if (ImportDesc.OriginalFirstThunk > 0)
            {
                pThunkRef = PtrAdd(pCode, ImportDesc.OriginalFirstThunk);
                pFuncRef = PtrAdd(pCode, ImportDesc.FirstThunk);
            }
            else
            {
                // no hint table
                pThunkRef = PtrAdd(pCode, ImportDesc.FirstThunk);
                pFuncRef = PtrAdd(pCode, ImportDesc.FirstThunk);
            }
            for (int SzRef = IntPtr.Size; ; pThunkRef = PtrAdd(pThunkRef, SzRef), pFuncRef = PtrAdd(pFuncRef, SzRef))
            {
                IntPtr ReadThunkRef = PtrRead<IntPtr>(pThunkRef), WriteFuncRef;
                if (ReadThunkRef == IntPtr.Zero) break;
                if (Win.IMAGE_SNAP_BY_ORDINAL(ReadThunkRef))
                {
                    WriteFuncRef = Win.GetProcAddress(handle, Win.IMAGE_ORDINAL(ReadThunkRef));
                }
                else
                {
                    WriteFuncRef = Win.GetProcAddress(handle, PtrAdd(PtrAdd(pCode, ReadThunkRef), Of.IMAGE_IMPORT_BY_NAME_Name));
                }
                if (WriteFuncRef == IntPtr.Zero) throw new DllException("Can't get adress for imported function");
                PtrWrite(pFuncRef, WriteFuncRef);
            }
        }
        return (ImportModules.Count > 0 ? ImportModules.ToArray() : null);
    }

19 View Source File : NativePluginDebug.cs
License : GNU Lesser General Public License v3.0
Project Creator : autocore-ai

static void Log(IntPtr strPtr) => Debug.Log($"{Const.unity_debug_plugin}:{Marshal.PtrToStringAnsi(strPtr)}");

19 View Source File : NativePluginDebug.cs
License : GNU Lesser General Public License v3.0
Project Creator : autocore-ai

static void LogWarning(IntPtr strPtr) => Debug.LogWarning($"{Const.unity_debug_plugin}:{Marshal.PtrToStringAnsi(strPtr)}");

19 View Source File : NativePluginDebug.cs
License : GNU Lesser General Public License v3.0
Project Creator : autocore-ai

static void LogError(IntPtr strPtr) => Debug.LogError($"{Const.unity_debug_plugin}:{Marshal.PtrToStringAnsi(strPtr)}");

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

public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName)
        {
            IntPtr FunctionPtr = IntPtr.Zero;
            try
            {
                // Traverse the PE header in memory
                Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));
                Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));
                Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;
                Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);
                Int64 pExport = 0;
                if (Magic == 0x010b)
                {
                    pExport = OptHeader + 0x60;
                }
                else
                {
                    pExport = OptHeader + 0x70;
                }

                // Read -> IMAGE_EXPORT_DIRECTORY
                Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);
                Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));
                Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));
                Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));
                Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));
                Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));
                Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));

                // Loop the array of export name RVA's
                for (int i = 0; i < NumberOfNames; i++)
                {
                    String FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
                    if (FunctionName.ToLower() == ExportName.ToLower())
                    {
                        Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
                        Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
                        FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
                        break;
                    }
                }
            }
            catch
            {
                // Catch parser failure
                throw new InvalidOperationException("Failed to parse module exports.");
            }

            if (FunctionPtr == IntPtr.Zero)
            {
                // Export not found
                throw new MissingMethodException(ExportName + ", export not found.");
            }
            return FunctionPtr;
        }

19 View Source File : Node.cs
License : GNU General Public License v3.0
Project Creator : BardMusicPlayer

void OnZeroTierEvent(IntPtr msgPtr)
        {
            zts_event_msg_t msg = (zts_event_msg_t)Marshal.PtrToStructure(msgPtr, typeof(zts_event_msg_t));
            Event newEvent = null;

            // Node

            if (msg.node != IntPtr.Zero) {
                zts_node_info_t details = (zts_node_info_t)Marshal.PtrToStructure(msg.node, typeof(zts_node_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                _id = details.node_id;
                _primaryPort = details.primary_port;
                _secondaryPort = details.secondary_port;
                _tertiaryPort = details.tertiary_port;
                _versionMajor = details.ver_major;
                _versionMinor = details.ver_minor;
                _versionRev = details.ver_rev;
                _isOnline = Convert.ToBoolean(zts_node_is_online());

                if (msg.event_code == Constants.EVENT_NODE_UP) {
                    newEvent.Name = "EVENT_NODE_UP";
                }
                if (msg.event_code == Constants.EVENT_NODE_ONLINE) {
                    newEvent.Name = "EVENT_NODE_ONLINE";
                }
                if (msg.event_code == Constants.EVENT_NODE_OFFLINE) {
                    newEvent.Name = "EVENT_NODE_OFFLINE";
                }
                if (msg.event_code == Constants.EVENT_NODE_DOWN) {
                    newEvent.Name = "EVENT_NODE_DOWN";
                }
                if (msg.event_code == Constants.ZTS_EVENT_NODE_FATAL_ERROR) {
                    newEvent.Name = "EVENT_NODE_FATAL_ERROR";
                }
            }

            // Network

            if (msg.network != IntPtr.Zero) {
                zts_net_info_t net_info = (zts_net_info_t)Marshal.PtrToStructure(msg.network, typeof(zts_net_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;

                // Update network info as long as we aren't tearing down the network
                if (msg.event_code != Constants.EVENT_NETWORK_DOWN) {
                    ulong networkId = net_info.net_id;
                    NetworkInfo ni = _networks.GetOrAdd(networkId, new NetworkInfo());

                    newEvent.NetworkInfo = ni;
                    newEvent.NetworkInfo.Id = net_info.net_id;
                    newEvent.NetworkInfo.MACAddress = net_info.mac;
                    newEvent.NetworkInfo.Name = System.Text.Encoding.UTF8.GetString(net_info.name);
                    newEvent.NetworkInfo.Status = net_info.status;
                    newEvent.NetworkInfo.Type = net_info.type;
                    newEvent.NetworkInfo.MTU = net_info.mtu;
                    newEvent.NetworkInfo.DHCP = net_info.dhcp;
                    newEvent.NetworkInfo.Bridge = Convert.ToBoolean(net_info.bridge);
                    newEvent.NetworkInfo.BroadcastEnabled = Convert.ToBoolean(net_info.broadcast_enabled);

                    zts_core_lock_obtain();

                    // Get replacedigned addresses

                    ConcurrentDictionary<string, IPAddress> newAddrsDict =
                        new ConcurrentDictionary<string, IPAddress>();
                    IntPtr addrBuffer = Marshal.AllocHGlobal(ZeroTier.Constants.INET6_ADDRSTRLEN);
                    int addr_count = zts_core_query_addr_count(networkId);

                    for (int idx = 0; idx < addr_count; idx++) {
                        zts_core_query_addr(networkId, idx, addrBuffer, ZeroTier.Constants.INET6_ADDRSTRLEN);
                        // Convert buffer to managed string
                        string str = Marshal.PtrToStringAnsi(addrBuffer);
                        IPAddress addr = IPAddress.Parse(str);
                        newAddrsDict[addr.ToString()] = addr;
                    }

                    // Update addresses in NetworkInfo object

                    // TODO: This update block works but could use a re-think, I think.
                    // Step 1. Remove addresses not present in new concurrent dict.
                    if (! ni._addrs.IsEmpty) {
                        foreach (string key in ni._addrs.Keys) {
                            if (! newAddrsDict.Keys.Contains(key)) {
                                ni._addrs.TryRemove(key, out _);
                            }
                        }
                    }
                    else {
                        ni._addrs = newAddrsDict;
                    }
                    // Step 2. Add addresses not present in existing concurrent dict.
                    foreach (string key in newAddrsDict.Keys) {
                        if (! ni._addrs.Keys.Contains(key)) {
                            ni._addrs[key] = newAddrsDict[key];
                        }
                    }

                    Marshal.FreeHGlobal(addrBuffer);
                    addrBuffer = IntPtr.Zero;

                    // Get managed routes

                    ConcurrentDictionary<string, RouteInfo> newRoutesDict =
                        new ConcurrentDictionary<string, RouteInfo>();
                    IntPtr targetBuffer = Marshal.AllocHGlobal(ZeroTier.Constants.INET6_ADDRSTRLEN);
                    IntPtr viaBuffer = Marshal.AllocHGlobal(ZeroTier.Constants.INET6_ADDRSTRLEN);

                    int route_count = zts_core_query_route_count(networkId);

                    ushort flags = 0, metric = 0;

                    for (int idx = 0; idx < route_count; idx++) {
                        zts_core_query_route(
                            networkId,
                            idx,
                            targetBuffer,
                            viaBuffer,
                            ZeroTier.Constants.INET6_ADDRSTRLEN,
                            ref flags,
                            ref metric);

                        // Convert buffer to managed string

                        try {
                            string targetStr = Marshal.PtrToStringAnsi(targetBuffer);
                            IPAddress targetAddr = IPAddress.Parse(targetStr);
                            string viaStr = Marshal.PtrToStringAnsi(viaBuffer);
                            IPAddress viaAddr = IPAddress.Parse(viaStr);
                            RouteInfo route = new RouteInfo(targetAddr, viaAddr, flags, metric);
                            // Add to NetworkInfo object
                            newRoutesDict[targetStr] = route;
                        }
                        catch {
                            Console.WriteLine("error while parsing route");
                        }
                    }

                    // TODO: This update block works but could use a re-think, I think.
                    // Step 1. Remove routes not present in new concurrent dict.
                    if (! ni._routes.IsEmpty) {
                        foreach (string key in ni._routes.Keys) {
                            if (! newRoutesDict.Keys.Contains(key)) {
                                ni._routes.TryRemove(key, out _);
                            }
                        }
                    }
                    else {
                        ni._routes = newRoutesDict;
                    }
                    // Step 2. Add routes not present in existing concurrent dict.
                    foreach (string key in newRoutesDict.Keys) {
                        if (! ni._routes.Keys.Contains(key)) {
                            ni._routes[key] = newRoutesDict[key];
                        }
                    }

                    Marshal.FreeHGlobal(targetBuffer);
                    Marshal.FreeHGlobal(viaBuffer);
                    targetBuffer = IntPtr.Zero;
                    viaBuffer = IntPtr.Zero;

                    // Get multicast subscriptions

                    zts_core_lock_release();

                    // Update synthetic "readiness" value
                    ni.transportReady = (route_count > 0) && (addr_count > 0) ? true : false;
                }   // EVENT_NETWORK_DOWN

                if (msg.event_code == Constants.EVENT_NETWORK_NOT_FOUND) {
                    newEvent.Name = "EVENT_NETWORK_NOT_FOUND " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_REQ_CONFIG) {
                    newEvent.Name = "EVENT_NETWORK_REQ_CONFIG " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_ACCESS_DENIED) {
                    newEvent.Name = "EVENT_NETWORK_ACCESS_DENIED " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_READY_IP4) {
                    newEvent.Name = "EVENT_NETWORK_READY_IP4 " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_READY_IP6) {
                    newEvent.Name = "EVENT_NETWORK_READY_IP6 " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_DOWN) {
                    newEvent.Name = "EVENT_NETWORK_DOWN " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_CLIENT_TOO_OLD) {
                    newEvent.Name = "EVENT_NETWORK_CLIENT_TOO_OLD " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_REQ_CONFIG) {
                    newEvent.Name = "EVENT_NETWORK_REQ_CONFIG " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_OK) {
                    newEvent.Name = "EVENT_NETWORK_OK " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_ACCESS_DENIED) {
                    newEvent.Name = "EVENT_NETWORK_ACCESS_DENIED " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_READY_IP4_IP6) {
                    newEvent.Name = "EVENT_NETWORK_READY_IP4_IP6 " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_UPDATE) {
                    newEvent.Name = "EVENT_NETWORK_UPDATE " + net_info.net_id.ToString("x16");
                }
            }

            // Route

            if (msg.route != IntPtr.Zero) {
                zts_route_info_t route_info =
                    (zts_route_info_t)Marshal.PtrToStructure(msg.route, typeof(zts_route_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                // newEvent.RouteInfo = default;   // new RouteInfo();

                if (msg.event_code == Constants.EVENT_ROUTE_ADDED) {
                    newEvent.Name = "EVENT_ROUTE_ADDED";
                }
                if (msg.event_code == Constants.EVENT_ROUTE_REMOVED) {
                    newEvent.Name = "EVENT_ROUTE_REMOVED";
                }
            }

            // Peer

            if (msg.peer != IntPtr.Zero) {
                zts_peer_info_t peer_info = (zts_peer_info_t)Marshal.PtrToStructure(msg.peer, typeof(zts_peer_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                // newEvent.PeerInfo = default;   // new PeerInfo();

                if (peer_info.role == Constants.PEER_ROLE_PLANET) {
                    newEvent.Name = "PEER_ROLE_PLANET";
                }
                if (msg.event_code == Constants.EVENT_PEER_DIRECT) {
                    newEvent.Name = "EVENT_PEER_DIRECT";
                }
                if (msg.event_code == Constants.EVENT_PEER_RELAY) {
                    newEvent.Name = "EVENT_PEER_RELAY";
                }
                // newEvent = new ZeroTier.Core.Event(msg.event_code,"EVENT_PEER_UNREACHABLE");
                if (msg.event_code == Constants.EVENT_PEER_PATH_DISCOVERED) {
                    newEvent.Name = "EVENT_PEER_PATH_DISCOVERED";
                }
                if (msg.event_code == Constants.EVENT_PEER_PATH_DEAD) {
                    newEvent.Name = "EVENT_PEER_PATH_DEAD";
                }
            }

            // Address

            if (msg.addr != IntPtr.Zero) {
                zts_addr_info_t unmanagedDetails =
                    (zts_addr_info_t)Marshal.PtrToStructure(msg.addr, typeof(zts_addr_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                // newEvent.AddressInfo = default;   // new AddressInfo();

                if (msg.event_code == Constants.EVENT_ADDR_ADDED_IP4) {
                    newEvent.Name = "EVENT_ADDR_ADDED_IP4";
                }
                if (msg.event_code == Constants.EVENT_ADDR_ADDED_IP6) {
                    newEvent.Name = "EVENT_ADDR_ADDED_IP6";
                }
                if (msg.event_code == Constants.EVENT_ADDR_REMOVED_IP4) {
                    newEvent.Name = "EVENT_ADDR_REMOVED_IP4";
                }
                if (msg.event_code == Constants.EVENT_ADDR_REMOVED_IP6) {
                    newEvent.Name = "EVENT_ADDR_REMOVED_IP6";
                }
            }

            // Storage

            if (msg.cache != IntPtr.Zero) {
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                // newEvent.AddressInfo = default;   // new AddressInfo();

                if (msg.event_code == Constants.EVENT_STORE_IDENreplacedY_SECRET) {
                    newEvent.Name = "EVENT_STORE_IDENreplacedY_SECRET";
                }
                if (msg.event_code == Constants.EVENT_STORE_IDENreplacedY_PUBLIC) {
                    newEvent.Name = "EVENT_STORE_IDENreplacedY_PUBLIC";
                }
                if (msg.event_code == Constants.EVENT_STORE_PLANET) {
                    newEvent.Name = "EVENT_STORE_PLANET";
                }
                if (msg.event_code == Constants.EVENT_STORE_PEER) {
                    newEvent.Name = "EVENT_STORE_PEER";
                }
                if (msg.event_code == Constants.EVENT_STORE_NETWORK) {
                    newEvent.Name = "EVENT_STORE_NETWORK";
                }
            }

            // Preplaced the converted Event to the managed callback (visible to user)
            if (newEvent != null) {
                _managedCallback(newEvent);
            }
        }

19 View Source File : Socket.cs
License : GNU General Public License v3.0
Project Creator : BardMusicPlayer

public Socket Accept()
        {
            if (_isClosed) {
                throw new ObjectDisposedException("Socket has been closed");
            }
            if (_fd < 0) {
                // Invalid file descriptor
                throw new SocketException((int)Constants.ERR_SOCKET);
            }
            if (_isListening == false) {
                throw new InvalidOperationException("Socket is not in a listening state. Call Listen() first");
            }
            IntPtr lpBuffer = Marshal.AllocHGlobal(ZeroTier.Constants.INET6_ADDRSTRLEN);
            int port = 0;
            int accepted_fd = zts_accept(_fd, lpBuffer, ZeroTier.Constants.INET6_ADDRSTRLEN, ref port);
            // Convert buffer to managed string
            string str = Marshal.PtrToStringAnsi(lpBuffer);
            Marshal.FreeHGlobal(lpBuffer);
            lpBuffer = IntPtr.Zero;
            IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Parse(str), port);
            Console.WriteLine("clientEndPoint = " + clientEndPoint.ToString());
            // Create new socket by providing file descriptor returned from zts_bsd_accept call.
            Socket clientSocket =
                new Socket(accepted_fd, _socketFamily, _socketType, _socketProtocol, _localEndPoint, clientEndPoint);
            return clientSocket;
        }

19 View Source File : RemoteControl_ssh.xaml.cs
License : Apache License 2.0
Project Creator : beckzhu

private void Error_Event(int level, IntPtr replacedle, IntPtr text, int lParam)
        {
            Dispatcher.Invoke(() =>
            {
                if (level == ERROR_FATAL) OnFatalError?.Invoke(Marshal.PtrToStringAnsi(replacedle), Marshal.PtrToStringAnsi(text));
                if (level == ERROR_NOTIC) OnNonfatal?.Invoke(Marshal.PtrToStringAnsi(replacedle), Marshal.PtrToStringAnsi(text));
            });
        }

19 View Source File : RemoteControl_ssh.xaml.cs
License : Apache License 2.0
Project Creator : beckzhu

private int SecurityAlert_Event(IntPtr text)
        {
            int ret = -1;
            MessageDialog.ButtnClick buttnClick = (type) =>
            {
                ret = type;
                if (ret == MessageDialog.IDCANCEL)
                {
                    Dispatcher.Invoke(() => { Closed?.Invoke(); });
                }
            };

            Dispatcher.Invoke(() =>
            {
                MessageDialog.Show(ParentControl, "安全警告", Marshal.PtrToStringAnsi(text), MessageDialog.MB_YESNOCANCEL,
                                   buttnClick, MessageDialog.IDCANCEL, 60);
            });

            while (true)
            {
                Thread.Sleep(15);
                if (ret >= 0) break;
            }

            return ret;
        }

19 View Source File : RemoteControl_ssh.xaml.cs
License : Apache License 2.0
Project Creator : beckzhu

private void Debug_Event(IntPtr text)
        {
            Debug.WriteLine(Marshal.PtrToStringAnsi(text));
        }

19 View Source File : RemoteControl_telnet.xaml.cs
License : Apache License 2.0
Project Creator : beckzhu

private void OnDebug(IntPtr text)
        {
            Debug.WriteLine(Marshal.PtrToStringAnsi(text));
        }

19 View Source File : NsfFile.cs
License : MIT License
Project Creator : BleuBleu

public static string[] GetSongNames(string filename)
        {
            var nsf = NsfOpen(filename);

            if (nsf == null)
                return null;

            var trackCount = NsfGetTrackCount(nsf);
            var trackNames = new string[trackCount];

            for (int i = 0; i < trackCount; i++)
            {
                var name = Marshal.PtrToStringAnsi(NsfGetTrackName(nsf, i));
                if (string.IsNullOrEmpty(name))
                {
                    trackNames[i] = $"Song {i+1}";
                }
                else
                {
                    trackNames[i] = name;
                }
            }

            NsfClose(nsf);

            return trackNames;
        }

19 View Source File : NsfFile.cs
License : MIT License
Project Creator : BleuBleu

public Project Load(string filename, int songIndex, int duration, int patternLength, int startFrame, bool removeIntroSilence, bool reverseDpcm, bool preserveDpcmPad)
        {
            nsf = NsfOpen(filename);

            if (nsf == null)
                return null;

            var trackCount = NsfGetTrackCount(nsf);

            if (songIndex < 0 || songIndex > trackCount)
                return null;

            preserveDpcmPadding = preserveDpcmPad;

            var palSource = (NsfIsPal(nsf) & 1) == 1;
            var numFrames = duration * (palSource ? 50 : 60);

            project = new Project();

            project.Name      = Marshal.PtrToStringAnsi(NsfGetreplacedle(nsf));
            project.Author    = Marshal.PtrToStringAnsi(NsfGetArtist(nsf));
            project.Copyright = Marshal.PtrToStringAnsi(NsfGetCopyright(nsf));
            project.PalMode   = palSource;

            // Our expansion mask is the same as NSF.
            var expansionMask = NsfGetExpansion(nsf);

            // The 2 upper bits of the mask need to be zero, we dont support these.
            if (expansionMask != (expansionMask & ExpansionType.AllMask))
            {
                Log.LogMessage(LogSeverity.Error, "NSF uses unknown or unsupported expansion chips, aborting.");
                NsfClose(nsf);
                return null;
            }

            var numN163Channels = (expansionMask & ExpansionType.N163Mask) != 0 ? GetNumNamcoChannels(filename, songIndex, numFrames) : 1;
            project.SetExpansionAudioMask(expansionMask, numN163Channels);

            var songName = Marshal.PtrToStringAnsi(NsfGetTrackName(nsf, songIndex));

            song = project.CreateSong(string.IsNullOrEmpty(songName) ? $"Song {songIndex + 1}" : songName);
            channelStates = new ChannelState[song.Channels.Length];

            NsfSetTrack(nsf, songIndex);

            song.ChangeFamiStudioTempoGroove(new[] { 1 }, false);
            song.SetDefaultPatternLength(patternLength);

            for (int i = 0; i < song.Channels.Length; i++)
                channelStates[i] = new ChannelState();

            var foundFirstNote = !removeIntroSilence;

            var p = 0;
            var n = 0;
            var f = startFrame;

            for (int i = 0; i < numFrames; i++)
            {
                p = f / song.PatternLength;
                n = f % song.PatternLength;

                if (p >= Song.MaxLength - 1)
                    break;

                var playCalled = 0;
                var waitFrameCount = 0;
                do
                {
                    playCalled = NsfRunFrame(nsf);

                    if (++waitFrameCount == 1000)
                    {
                        Log.LogMessage(LogSeverity.Error, "NSF did not call PLAY after 1000 frames, aborting.");
                        NsfClose(nsf);
                        return null;
                    }
                }
                while (playCalled == 0);

                for (int c = 0; c < song.Channels.Length; c++)
                    foundFirstNote |= UpdateChannel(p, n, song.Channels[c], channelStates[c]);

                if (foundFirstNote)
                {
                    f++;
                }
                else
                {
                    // Reset everything until we find our first note.
                    project.DeleteAllInstruments();
                    project.DeleteAllSamples();
                    for (int c = 0; c < song.Channels.Length; c++)
                        channelStates[c] = new ChannelState();
                }
            }

            song.SetLength(p + 1);

            NsfClose(nsf);

            var factors = Utils.GetFactors(song.PatternLength, FamiStudioTempoUtils.MaxNoteLength);
            if (factors.Length > 0)
            {
                var noteLen = factors[0];

                // Look for a factor that generates a note length < 10 and gives a pattern length that is a multiple of 16.
                foreach (var factor in factors)
                {
                    if (factor <= 10)
                    {
                        noteLen = factor;
                        if (((song.PatternLength / noteLen) % 16) == 0)
                            break;
                    }
                }
                                
                song.ChangeFamiStudioTempoGroove(new[] { noteLen }, false);
            }
            else
                song.ChangeFamiStudioTempoGroove(new[] { 1 }, false);

            song.SetSensibleBeatLength();
            song.ConvertToCompoundNotes();
            song.DeleteEmptyPatterns();
            song.UpdatePatternStartNotes();
            song.InvalidatereplacedulativePatternCache();
            project.DeleteUnusedInstruments();

            foreach (var sample in project.Samples)
                sample.ReverseBits = reverseDpcm;

            return project;
        }

19 View Source File : MacUtils.cs
License : MIT License
Project Creator : BleuBleu

public static unsafe string FromNSURL(IntPtr url)
        {
            var str = SendIntPtr(url, selPath);
            var charPtr = SendIntPtr(str, selUTF8String);
            return Marshal.PtrToStringAnsi(charPtr);
        }

19 View Source File : RtMidi.cs
License : MIT License
Project Creator : BleuBleu

public static unsafe string GetDeviceName(int idx)
        {
            return Marshal.PtrToStringAnsi(rtmidi_get_port_name(midiIn, idx));
        }

19 View Source File : ViveMediaDecoder.cs
License : MIT License
Project Creator : bodhid

public static void getMetaData(string filePath, out string[] key, out string[] value) {
			IntPtr keyptr = IntPtr.Zero;
			IntPtr valptr = IntPtr.Zero;

			int metaCount = nativeGetMetaData(filePath, out keyptr, out valptr);

			IntPtr[] keys = new IntPtr[metaCount];
			IntPtr[] vals = new IntPtr[metaCount];
			Marshal.Copy(keyptr, keys, 0, metaCount);
			Marshal.Copy(valptr, vals, 0, metaCount);

			string[] keyArray = new string[metaCount];
			string[] valArray = new string[metaCount];
			for (int i = 0; i < metaCount; i++) {
				keyArray[i] = Marshal.PtrToStringAnsi(keys[i]);
				valArray[i] = Marshal.PtrToStringAnsi(vals[i]);
				Marshal.FreeCoTaskMem(keys[i]);
				Marshal.FreeCoTaskMem(vals[i]);
			}
			Marshal.FreeCoTaskMem(keyptr);
			Marshal.FreeCoTaskMem(valptr);

			key = keyArray;
			value = valArray;
		}

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

static string GetUsernameBySessionId(IntPtr serverHandle, int sessionId)
        {
            IntPtr buffer;
            uint strLen;
            var username = "";
            if (Win32.WTSQuerySessionInformation(serverHandle, sessionId, Win32.WTS_INFO_CLreplaced.WTSUserName, out buffer, out strLen) && strLen > 1)
            {
                username = Marshal.PtrToStringAnsi(buffer); // don't need length as these are null terminated strings
                Win32.WTSFreeMemory(buffer);
                if (Win32.WTSQuerySessionInformation(serverHandle, sessionId, Win32.WTS_INFO_CLreplaced.WTSDomainName, out buffer, out strLen) && strLen > 1)
                {
                    username = Marshal.PtrToStringAnsi(buffer) + "\\" + username; // prepend domain name
                    Win32.WTSFreeMemory(buffer);
                }
            }
            return username;
        }

19 View Source File : OsInfo.cs
License : GNU General Public License v3.0
Project Creator : bonarr

[DebuggerStepThrough]
        static bool IsRunningOnMac()
        {
            var buf = IntPtr.Zero;

            try
            {
                buf = Marshal.AllocHGlobal(8192);
                // This is a hacktastic way of getting sysname from uname ()
                if (uname(buf) == 0)
                {
                    var os = Marshal.PtrToStringAnsi(buf);

                    if (os == "Darwin")
                    {
                        return true;
                    }
                }
            }
            catch
            {
            }
            finally
            {
                if (buf != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buf);
                }
            }

            return false;
        }

19 View Source File : MediaInfoLib.cs
License : GNU General Public License v3.0
Project Creator : bonarr

private string MakeStringResult(IntPtr value)
        {
            if (Encoding == Encoding.Unicode)
            {
                return Marshal.PtrToStringUni(value);
            }
            else if (Encoding == Encoding.UTF32)
            {
                int i = 0;
                for (; i < 1024; i += 4)
                {
                    var data = Marshal.ReadInt32(value, i);
                    if (data == 0)
                    {
                        break;
                    }
                }

                var buffer = new byte[i];
                Marshal.Copy(value, buffer, 0, i);

                return Encoding.GetString(buffer, 0, i);
            }
            else
            {
                return Marshal.PtrToStringAnsi(value);
            }
        }

19 View Source File : OVRPlugin.cs
License : MIT License
Project Creator : bonzajplc

public static string ovrp_GetVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetVersion()); }

19 View Source File : OVRPlugin.cs
License : MIT License
Project Creator : bonzajplc

public static string ovrp_GetNativeSDKVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetNativeSDKVersion()); }

19 View Source File : OVRPlugin.cs
License : MIT License
Project Creator : bonzajplc

public static string ovrp_GetSystemProductName() { return Marshal.PtrToStringAnsi(_ovrp_GetSystemProductName()); }

See More Examples