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 Source : WTSAPI32.cs
with GNU Affero General Public License v3.0
from hamflx

public static string GetUserNameBySessionId(int dwSessionId)
        {
            IntPtr buffer;
            uint strLen;
            var username = "System";
            if (WTSQuerySessionInformation(IntPtr.Zero, dwSessionId, WTSInfoClreplaced.WTSUserName, out buffer, out strLen) && strLen > 1)
            {
                username = Marshal.PtrToStringAnsi(buffer);
                WTSFreeMemory(buffer);
            }
            return username;
        }

19 Source : Common.cs
with Apache License 2.0
from HanJunJun

public static string PtrToAnsiString(IntPtr ptr)
        {
            string str = "";
            try
            {
                if (ptr != IntPtr.Zero)
                {
                    str = Marshal.PtrToStringAnsi(ptr);
                }
            }
            catch (Exception)
            {
            }
            return str;
        }

19 Source : JsValue.cs
with GNU General Public License v3.0
from HMBSbige

public string[] GetKeys(IntPtr jsExecState)
        {
            IntPtr jsKeys = MBApi.jsGetKeys(jsExecState, this.Value);
            if(jsKeys!=IntPtr.Zero)
            {
                int len = Marshal.ReadInt32(jsKeys);
                int sizePtr = Marshal.SizeOf(typeof(IntPtr));
                IntPtr ppKeys = Marshal.ReadIntPtr(jsKeys, sizePtr );
                string[] keys = new string[len];
                for (int i = 0; i < len; i++)
                {
                    keys[i] = Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(ppKeys, sizePtr * i));
                }
                return keys;
            }
            return null;
        }

19 Source : MpResourceHandle.cs
with MIT License
from homuler

protected string MarshalStringFromNative(StringOutFunc f)
    {
      f(mpPtr, out var strPtr).replacedert();
      GC.KeepAlive(this);

      var str = Marshal.PtrToStringAnsi(strPtr);
      UnsafeNativeMethods.delete_array__PKc(strPtr);

      return str;
    }

19 Source : FreeType.cs
with MIT License
from huangx916

static public string[] GetFaces (Font font)
	{
		if (font == null || !isPresent) return null;

		string[] names = null;
		IntPtr lib = IntPtr.Zero;
		IntPtr face = IntPtr.Zero;

		if (FT_Init_FreeType(out lib) != 0)
		{
			Debug.LogError("Failed to initialize FreeType");
			return null;
		}

		string fileName = Application.dataPath.Substring(0, Application.dataPath.Length - "replacedets".Length) +
			UnityEditor.replacedetDatabase.GetreplacedetPath(font);

		if (File.Exists(fileName))
		{
			if (FT_New_Face(lib, fileName, 0, out face) != 0)
			{
				Debug.LogError("Unable to use the chosen font (FT_New_Face).");
			}
			else
			{
				FT_FaceRec record = (FT_FaceRec)Marshal.PtrToStructure(face, typeof(FT_FaceRec));
				names = new string[record.num_faces];

				for (int i = 0; i < record.num_faces; i++)
				{
					IntPtr ptr = IntPtr.Zero;

					if (FT_New_Face(lib, fileName, i, out ptr) == 0)
					{
						string family = Marshal.PtrToStringAnsi(record.family_name);
						string style = Marshal.PtrToStringAnsi(record.style_name);
						names[i] = family + " - " + style;
						FT_Done_Face(ptr);
					}
				}
			}
		}
		if (face != IntPtr.Zero) FT_Done_Face(face);
#if !UNITY_3_5
		if (lib != IntPtr.Zero) FT_Done_FreeType(lib);
#endif
		return names;
	}

19 Source : Extensions.cs
with Apache License 2.0
from int2e

internal static string PtrToAnsiString(this IntPtr ptr)
        {
            var str = string.Empty;
            try
            {
                if (ptr != IntPtr.Zero)
                {
                    str = Marshal.PtrToStringAnsi(ptr);
                }
            }
            catch
            {
                // ignored
            }

            return str;
        }

19 Source : RapidlibLinkerDLL.cs
with MIT License
from Interactml

public static string RunSeriesClreplacedification(IntPtr model, IntPtr runningSeries)
        {
            if (model == IntPtr.Zero)
                throw new Exception("The address to the model is zero, aborting runSeriesClreplacedification.");

            string outputString = "";
            try
            {
                outputString = Marshal.PtrToStringAnsi(runSeriesClreplacedification(model, runningSeries));
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                throw new Exception("Error when running dtw model: " + e.Message);
            }
            return outputString;
        }

19 Source : RapidlibLinkerDLL.cs
with MIT License
from Interactml

public static string GetJSON(IntPtr model)
        {
            if (model == IntPtr.Zero)
                throw new Exception("The address to the model is zero, aborting GetJSON.");

            return Marshal.PtrToStringAnsi(getJSON(model));
        }

19 Source : SdpDiscoveryRecordsBuffer.cs
with MIT License
from inthehand

public ServiceRecord[] GetServiceRecords()
        {
            Debug.replacedert(m_request.searchScope == SdpSearchScope.Anywhere, "unexpected searchScope: " + m_request.searchScope);
            int clreplacedInSCL, clreplacedAnywhere;
            if (m_records == null) {
                m_records = new List<ServiceRecord>();
                SdpDiscoveryRecordsBufferBase.SimpleInfo[] infoArr = GetSimpleInfo();
                foreach (SdpDiscoveryRecordsBufferBase.SimpleInfo info in infoArr) {
                    clreplacedInSCL = clreplacedAnywhere = 0;
                    //Utils.MiscUtils.Trace_WriteLine("fake int: {0}", info.fake);
                    ServiceRecordBuilder bldr = new ServiceRecordBuilder();
                    const ServiceAttributeId FakeDescr = (ServiceAttributeId)(-1);
                    bldr.AddCustomAttribute(new ServiceAttribute(FakeDescr,
                        new ServiceElement(ElementType.TextString,
                            "<partial Widcomm decode>")));
                    //--
                    bldr.AddServiceClreplaced(info.serviceUuid);
                    if (m_request.serviceGuid == info.serviceUuid)
                        ++clreplacedInSCL;
                    //--
                    if (info.serviceNameWchar != IntPtr.Zero) {
                        string name = Marshal.PtrToStringUni(info.serviceNameWchar);
                        if (name.Length != 0)
                            bldr.ServiceName = name;
                    } else if (info.serviceNameChar != IntPtr.Zero) {
                        // PtrToStringAnsi is not supported on NETCF.  The field 
                        // is not used by the native code there so that's ok.
#if NETCF
                        Debug.Fail("Don't expect 'serviceNameChar' on PPC.");
#else
                        string name = Marshal.PtrToStringAnsi(info.serviceNameChar);
                        if (name.Length != 0)
                            bldr.ServiceName = name;
#endif
                    }
                    //--
                    if (info.scn == -1) {
                        bldr.ProtocolType = BluetoothProtocolDescriptorType.None;
                    }
                    //--
                    switch (bldr.ProtocolType) {
                        case BluetoothProtocolDescriptorType.GeneralObex:
                            Debug.Fail("GEOP untested");
                            if (m_request.serviceGuid == BluetoothService.ObexProtocol)
                                ++clreplacedAnywhere;
                            goto case BluetoothProtocolDescriptorType.Rfcomm;
                        case BluetoothProtocolDescriptorType.Rfcomm:
                            if (m_request.serviceGuid == BluetoothService.RFCommProtocol)
                                ++clreplacedAnywhere;
                            if (m_request.serviceGuid == BluetoothService.L2CapProtocol)
                                ++clreplacedAnywhere;
                            break;
                        case BluetoothProtocolDescriptorType.None:
                            // We'd better replacedume L2CAP in the PDL or we'd skip too many
                            // e.g. the SDP server record!
                            if (m_request.serviceGuid == BluetoothService.L2CapProtocol)
                                ++clreplacedAnywhere;
                            break;
                    }
                    //--
                    ServiceRecord sr = bldr.ServiceRecord;
                    if (info.scn != -1) {
                        Debug.replacedert(bldr.ProtocolType == BluetoothProtocolDescriptorType.Rfcomm,
                            "type=" + bldr.ProtocolType);
                        ServiceRecordHelper.SetRfcommChannelNumber(sr, checked((byte)info.scn));
                    }
                    if (clreplacedInSCL > 0 || clreplacedAnywhere > 0) {
                        Utils.MiscUtils.Trace_WriteLine("Adding record");
                        m_records.Add(sr);
                    } else { // COVERAGE
                        Utils.MiscUtils.Trace_WriteLine("Skipping record");
                    }
                }
            }
            return m_records.ToArray();
        }

19 Source : CaptureNamesEnumerator.cs
with MIT License
from iwillspeak

public bool MoveNext()
        {
            while (RureFfi.rure_iter_capture_names_next(_handle, out IntPtr name))
            {
                Current = Marshal.PtrToStringAnsi(name);
                if (!string.IsNullOrEmpty(Current))
                    return true;
            }
            return false;
        }

19 Source : Stats.cs
with MIT License
from jeikabu

public static string nng_stat_desc_string(nng_stat statsp)
        {
            unsafe
            {
                var ptr = new IntPtr(nng_stat_desc(statsp));
                return Marshal.PtrToStringAnsi(ptr);
            }
        }

19 Source : Stats.cs
with MIT License
from jeikabu

public static string nng_stat_string_string(nng_stat statsp)
        {
            unsafe
            {
                var ptr = new IntPtr(nng_stat_string(statsp));
                return Marshal.PtrToStringAnsi(ptr);
            }
        }

19 Source : Stats.cs
with MIT License
from jeikabu

public static string nng_stat_name_string(nng_stat statsp)
        {
            unsafe
            {
                var ptr = new IntPtr(nng_stat_name(statsp));
                return Marshal.PtrToStringAnsi(ptr);
            }
        }

19 Source : String.cs
with MIT License
from jeikabu

public string ToManaged()
        {
            return Marshal.PtrToStringAnsi(Ptr);
        }

19 Source : Helper.Unix.cs
with Apache License 2.0
from JetBrains

private static string GetSysnameFromUname()
    {
      var buf = Marshal.AllocHGlobal(8 * 1024);
      try
      {
        if (LibC.uname(buf) != 0)
          throw new Exception("Failed to get Unix system name");

        // Note: utsname::sysname is the first member of structure, so simple take it!
        return Marshal.PtrToStringAnsi(buf);
      }
      finally
      {
        Marshal.FreeHGlobal(buf);
      }
    }

19 Source : Helper.Unix.cs
with Apache License 2.0
from JetBrains

private static Tuple<PlatformId, ArchitectureId> DeduceUnixConfig()
    {
      var buf = IntPtr.Zero;
      try
      {
        // from sys/utsname.h:
        // struct utsname
        // {
        //   char sysname[NAMELEN];
        //   char nodename[NAMELEN];
        //   char release[NAMELEN];
        //   char version[NAMELEN];
        //   char machine[NAMELEN];
        // };

        buf = Marshal.AllocHGlobal(8192);
        var rc = LibC.uname(buf);
        if (rc != 0)
          throw new Exception("uname() was failed with errno " + Marshal.GetLastWin32Error());

        var platform = ToPlatformId(Marshal.PtrToStringAnsi(buf));
        var nameLen = platform.ToNameLen();
        const int machineIndex = 4;
        return Tuple.Create(platform, ToArchitecture(Marshal.PtrToStringAnsi(buf + machineIndex * nameLen)));
      }
      finally
      {
        if (buf != IntPtr.Zero)
          Marshal.FreeHGlobal(buf);
      }
    }

19 Source : Generic.cs
with Apache License 2.0
from jfmaes

public static IntPtr GetExportAddress(IntPtr ModuleBase, string FunctionHash, long Key, bool ResolveForwards = true)
        {
            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 (GetAPIHash(FunctionName, Key).Equals(FunctionHash, 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);

                        if (ResolveForwards == true)
                            // If the export address points to a forward, get the address
                            FunctionPtr = GetForwardAddress(FunctionPtr);

                        break;
                    }
                }
            }
            catch
            {
                // Catch parser failure
                throw new InvalidOperationException("Failed to parse module exports.");
            }

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

19 Source : Generic.cs
with Apache License 2.0
from jfmaes

public static IntPtr GetForwardAddress(IntPtr ExportAddress, bool CanLoadFromDisk = false)
        {
            IntPtr FunctionPtr = ExportAddress;
            try
            {
                // replacedume it is a forward. If it is not, we will get an error
                string ForwardNames = Marshal.PtrToStringAnsi(FunctionPtr);
                string[] values = ForwardNames.Split('.');

                if (values.Length > 1)
                {
                    string ForwardModuleName = values[0];
                    string ForwardExportName = values[1];

                    // Check if it is an API Set mapping
                    Dictionary<string, string> ApiSet = GetApiSetMapping();
                    string LookupKey = ForwardModuleName.Substring(0, ForwardModuleName.Length - 2) + ".dll";
                    if (ApiSet.ContainsKey(LookupKey))
                        ForwardModuleName = ApiSet[LookupKey];
                    else
                        ForwardModuleName = ForwardModuleName + ".dll";

                    IntPtr hModule = GetPebLdrModuleEntry(ForwardModuleName);
                    if (hModule == IntPtr.Zero && CanLoadFromDisk == true)
                        hModule = LoadModuleFromDisk(ForwardModuleName);
                    if (hModule != IntPtr.Zero)
                    {
                        FunctionPtr = GetExportAddress(hModule, ForwardExportName);
                    }
                }
            }
            catch
            {
                // Do nothing, it was not a forward
            }
            return FunctionPtr;
        }

19 Source : Generic.cs
with Apache License 2.0
from jfmaes

public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName, bool ResolveForwards = true)
        {
            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));

                // Get the VAs of the name table's beginning and end.
                Int64 NamesBegin = ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA));
                Int64 NamesFinal = NamesBegin + NumberOfNames * 4;

                // 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.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);
                        
                        if (ResolveForwards == true)
                            // If the export address points to a forward, get the address
                            FunctionPtr = GetForwardAddress(FunctionPtr);

                        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 Source : Map.cs
with Apache License 2.0
from jfmaes

public static void RewriteModuleIAT(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)
        {
            Data.PE.IMAGE_DATA_DIRECTORY idd = PEINFO.Is32Bit ? PEINFO.OptHeader32.ImportTable : PEINFO.OptHeader64.ImportTable;

            // Check if there is no import table
            if (idd.VirtualAddress == 0)
            {
                // Return so that the rest of the module mapping process may continue.
                return;
            }

            // Ptr for the base import directory
            IntPtr pImportTable = (IntPtr)((UInt64)ModuleMemoryBase + idd.VirtualAddress);

            // Get API Set mapping dictionary if on Win10+
            Data.Native.OSVERSIONINFOEX OSVersion = new Data.Native.OSVERSIONINFOEX();
            DynamicInvoke.Native.RtlGetVersion(ref OSVersion);
            Dictionary<string, string> ApiSetDict = new Dictionary<string, string>();
            if (OSVersion.MajorVersion >= 10)
            {
                ApiSetDict = DynamicInvoke.Generic.GetApiSetMapping();
            }

            // Loop IID's
            int counter = 0;
            Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR iid = new Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR();
            iid = (Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)Marshal.PtrToStructure(
                (IntPtr)((UInt64)pImportTable + (uint)(Marshal.SizeOf(iid) * counter)),
                typeof(Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)
            );
            while (iid.Name != 0)
            {
                // Get DLL
                string DllName = string.Empty;
                try
                {
                    DllName = Marshal.PtrToStringAnsi((IntPtr)((UInt64)ModuleMemoryBase + iid.Name));
                }
                catch { }

                // Loop imports
                if (DllName == string.Empty)
                {
                    throw new InvalidOperationException("Failed to read DLL name.");
                }
                else
                {
                    string LookupKey = DllName.Substring(0, DllName.Length - 6) + ".dll";
                    // API Set DLL? Ignore the patch number.
                    if (OSVersion.MajorVersion >= 10 && (DllName.StartsWith("api-") || DllName.StartsWith("ext-")) &&
                        ApiSetDict.ContainsKey(LookupKey) && ApiSetDict[LookupKey].Length > 0)
                    {
                        // Not all API set DLL's have a registered host mapping
                        DllName = ApiSetDict[LookupKey];
                    }

                    // Check and / or load DLL
                    IntPtr hModule = DynamicInvoke.Generic.GetLoadedModuleAddress(DllName);
                    if (hModule == IntPtr.Zero)
                    {
                        hModule = DynamicInvoke.Generic.LoadModuleFromDisk(DllName);
                        if (hModule == IntPtr.Zero)
                        {
                            throw new FileNotFoundException(DllName + ", unable to find the specified file.");
                        }
                    }

                    // Loop thunks
                    if (PEINFO.Is32Bit)
                    {
                        Data.PE.IMAGE_THUNK_DATA32 oft_itd = new Data.PE.IMAGE_THUNK_DATA32();
                        for (int i = 0; true; i++)
                        {
                            oft_itd = (Data.PE.IMAGE_THUNK_DATA32)Marshal.PtrToStructure((IntPtr)((UInt64)ModuleMemoryBase + iid.OriginalFirstThunk + (UInt32)(i * (sizeof(UInt32)))), typeof(Data.PE.IMAGE_THUNK_DATA32));
                            IntPtr ft_itd = (IntPtr)((UInt64)ModuleMemoryBase + iid.FirstThunk + (UInt64)(i * (sizeof(UInt32))));
                            if (oft_itd.AddressOfData == 0)
                            {
                                break;
                            }

                            if (oft_itd.AddressOfData < 0x80000000) // !IMAGE_ORDINAL_FLAG32
                            {
                                IntPtr pImpByName = (IntPtr)((UInt64)ModuleMemoryBase + oft_itd.AddressOfData + sizeof(UInt16));
                                IntPtr pFunc = IntPtr.Zero;
                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, Marshal.PtrToStringAnsi(pImpByName));

                                // Write ProcAddress
                                Marshal.WriteInt32(ft_itd, pFunc.ToInt32());
                            }
                            else
                            {
                                ulong fOrdinal = oft_itd.AddressOfData & 0xFFFF;
                                IntPtr pFunc = IntPtr.Zero;
                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, (short)fOrdinal);

                                // Write ProcAddress
                                Marshal.WriteInt32(ft_itd, pFunc.ToInt32());
                            }
                        }
                    }
                    else
                    {
                        Data.PE.IMAGE_THUNK_DATA64 oft_itd = new Data.PE.IMAGE_THUNK_DATA64();
                        for (int i = 0; true; i++)
                        {
                            oft_itd = (Data.PE.IMAGE_THUNK_DATA64)Marshal.PtrToStructure((IntPtr)((UInt64)ModuleMemoryBase + iid.OriginalFirstThunk + (UInt64)(i * (sizeof(UInt64)))), typeof(Data.PE.IMAGE_THUNK_DATA64));
                            IntPtr ft_itd = (IntPtr)((UInt64)ModuleMemoryBase + iid.FirstThunk + (UInt64)(i * (sizeof(UInt64))));
                            if (oft_itd.AddressOfData == 0)
                            {
                                break;
                            }

                            if (oft_itd.AddressOfData < 0x8000000000000000) // !IMAGE_ORDINAL_FLAG64
                            {
                                IntPtr pImpByName = (IntPtr)((UInt64)ModuleMemoryBase + oft_itd.AddressOfData + sizeof(UInt16));
                                IntPtr pFunc = IntPtr.Zero;
                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, Marshal.PtrToStringAnsi(pImpByName));

                                // Write pointer
                                Marshal.WriteInt64(ft_itd, pFunc.ToInt64());
                            }
                            else
                            {
                                ulong fOrdinal = oft_itd.AddressOfData & 0xFFFF;
                                IntPtr pFunc = IntPtr.Zero;
                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, (short)fOrdinal);

                                // Write pointer
                                Marshal.WriteInt64(ft_itd, pFunc.ToInt64());
                            }
                        }
                    }

                    // Go to the next IID
                    counter++;
                    iid = (Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)Marshal.PtrToStructure(
                        (IntPtr)((UInt64)pImportTable + (uint)(Marshal.SizeOf(iid) * counter)),
                        typeof(Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)
                    );
                }
            }
        }

19 Source : DllContext.cs
with MIT License
from jglim

public string GetECUName()
        {
            IntPtr procAddress = dllAddressMappings["GetECUName"];
            if (procAddress == IntPtr.Zero)
            {
                return "(unavailable)";
            }
            var fn = (ExportDefinition.GetECUName)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(ExportDefinition.GetECUName));
            IntPtr resultPtr = fn();
            return Marshal.PtrToStringAnsi(resultPtr);
        }

19 Source : DllContext.cs
with MIT License
from jglim

public string GetComment()
        {
            IntPtr procAddress = dllAddressMappings["GetComment"];
            if (procAddress == IntPtr.Zero)
            {
                return "(unavailable)";
            }
            var fn = (ExportDefinition.GetComment)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(ExportDefinition.GetComment));
            IntPtr resultPtr = fn();
            return Marshal.PtrToStringAnsi(resultPtr);
        }

19 Source : SetupApi.cs
with MIT License
from Jinjinov

private static string GetDeviceId(uint inst)
        {
            IntPtr buffer = Marshal.AllocHGlobal(MAX_DEVICE_ID_LEN + 1);
            int cr = CM_Get_Device_ID(inst, buffer, MAX_DEVICE_ID_LEN + 1, 0);
            if (cr != 0)
                throw new Exception("CM Error:" + cr);

            try
            {
                return Marshal.PtrToStringAnsi(buffer) ?? string.Empty;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

19 Source : PublicationBuiltinTopicData.cs
with GNU Lesser General Public License v3.0
from jmmorato

internal void FromNative(PublicationBuiltinTopicDataWrapper wrapper)
        {
            Deadline = wrapper.Deadline;
            DestinationOrder = wrapper.DestinationOrder;
            Durability = wrapper.Durability;
            DurabilityService = wrapper.DurabilityService;
            Key = wrapper.Key;
            LatencyBudget = wrapper.LatencyBudget;
            Lifespan = wrapper.Lifespan;
            Liveliness = wrapper.Liveliness;
            Ownership = wrapper.Ownership;
            OwnershipStrength = wrapper.OwnershipStrength;
            ParticipantKey = wrapper.ParticipantKey;
            Presentation = wrapper.Presentation;
            Reliability = wrapper.Reliability;

            if (Parreplacedion == null)
            {
                Parreplacedion = new ParreplacedionQosPolicy();
            }
            Parreplacedion.FromNative(wrapper.Parreplacedion);

            if (GroupData == null)
            {
                GroupData = new GroupDataQosPolicy();
            }
            GroupData.FromNative(wrapper.GroupData);

            if (TopicData == null)
            {
                TopicData = new TopicDataQosPolicy();
            }
            TopicData.FromNative(wrapper.TopicData);

            if (UserData == null)
            {
                UserData = new UserDataQosPolicy();
            }
            UserData.FromNative(wrapper.UserData);

            if (wrapper.TopicName != IntPtr.Zero)
            {
                TopicName = Marshal.PtrToStringAnsi(wrapper.TopicName);
            }
            else
            {
                TopicName = null;
            }

            if (wrapper.TypeName != IntPtr.Zero)
            {
                TypeName = Marshal.PtrToStringAnsi(wrapper.TypeName);
            }
            else
            {
                TypeName = null;
            }
        }

19 Source : TopicDescription.cs
with GNU Lesser General Public License v3.0
from jmmorato

private string GetTypeName()
        {
            return Marshal.PtrToStringAnsi(UnsafeNativeMethods.GetTypeName(_native));
        }

19 Source : TopicDescription.cs
with GNU Lesser General Public License v3.0
from jmmorato

private string GetName()
        {
            return Marshal.PtrToStringAnsi(UnsafeNativeMethods.GetName(_native));
        }

19 Source : Discovery.cs
with GNU Lesser General Public License v3.0
from jmmorato

private string GetKey()
        {
            var ptr = UnsafeNativeMethods.GetKey(_native);

            var key = Marshal.PtrToStringAnsi(ptr);
            ptr.ReleaseNativePointer();

            return key;
        }

19 Source : MarshalHelper.cs
with GNU Lesser General Public License v3.0
from jmmorato

public static void PtrToStringSequence(this IntPtr ptr, ref IList<string> sequence, bool isUnicode, int capacity = 0)
    {
        // Ensure a not null empty list to populate
        if (sequence == null)
        {
            if (capacity > 0)
                sequence = new List<string>(capacity);
            else
                sequence = new List<string>();
        }
        else
        {
            sequence.Clear();
        }

        if (ptr == IntPtr.Zero)
            return;

        // Start by reading the size of the array
        int length = Marshal.ReadInt32(ptr);

        // Populate the array
        for (int i = 0; i < length; i++)
        {
            // Get the unmanaged pointer
            IntPtr pointer = Marshal.PtrToStructure<IntPtr>(ptr + sizeof(int) + (IntPtr.Size * i));

            // Convert the pointer in a string
            if (isUnicode)
                sequence.Add(PtrToWideString(pointer));
            else
                sequence.Add(Marshal.PtrToStringAnsi(pointer));
        }
    }

19 Source : QueryCondition.cs
with GNU Lesser General Public License v3.0
from jmmorato

private string GetQueryExpresion()
        {
            return Marshal.PtrToStringAnsi(UnsafeNativeMethods.GetQueryExpresion(_native));
        }

19 Source : SubscriptionBuiltinTopicData.cs
with GNU Lesser General Public License v3.0
from jmmorato

internal void FromNative(SubscriptionBuiltinTopicDataWrapper wrapper)
        {
            Deadline = wrapper.Deadline;
            DestinationOrder = wrapper.DestinationOrder;
            Durability = wrapper.Durability;
            Key = wrapper.Key;
            LatencyBudget = wrapper.LatencyBudget;
            Liveliness = wrapper.Liveliness;
            Ownership = wrapper.Ownership;
            ParticipantKey = wrapper.ParticipantKey;
            Presentation = wrapper.Presentation;
            Reliability = wrapper.Reliability;
            TimeBasedFilter = wrapper.TimeBasedFilter;

            if (Parreplacedion == null)
            {
                Parreplacedion = new ParreplacedionQosPolicy();
            }
            Parreplacedion.FromNative(wrapper.Parreplacedion);

            if (GroupData == null)
            {
                GroupData = new GroupDataQosPolicy();
            }
            GroupData.FromNative(wrapper.GroupData);

            if (TopicData == null)
            {
                TopicData = new TopicDataQosPolicy();
            }
            TopicData.FromNative(wrapper.TopicData);

            if (UserData == null)
            {
                UserData = new UserDataQosPolicy();
            }
            UserData.FromNative(wrapper.UserData);

            if (wrapper.TopicName != IntPtr.Zero)
            {
                TopicName = Marshal.PtrToStringAnsi(wrapper.TopicName);
            }
            else
            {
                TopicName = null;
            }

            if (wrapper.TypeName != IntPtr.Zero)
            {
                TypeName = Marshal.PtrToStringAnsi(wrapper.TypeName);
            }
            else
            {
                TypeName = null;
            }
        }

19 Source : MarshalHelper.cs
with GNU Lesser General Public License v3.0
from jmmorato

public static void PtrToStringSequence(this IntPtr ptr, ref IList<string> sequence, bool isUnicode, int capacity = 0)
        {
            // Ensure a not null empty list to populate
            if (sequence == null)
            {
                if (capacity > 0)
                {
                    sequence = new List<string>(capacity);
                }
                else
                {
                    sequence = new List<string>();
                }
            }
            else
            {
                sequence.Clear();
            }

            if (ptr == IntPtr.Zero)
            {
                return;
            }

            // Start by reading the size of the array
            int length = Marshal.ReadInt32(ptr);

            // Populate the array
            for (int i = 0; i < length; i++)
            {
                // Get the unmanaged pointer
                IntPtr pointer = Marshal.PtrToStructure<IntPtr>(ptr + sizeof(int) + (IntPtr.Size * i));

                // Convert the pointer in a string
                if (isUnicode)
                {
                    sequence.Add(Marshal.PtrToStringUni(pointer));
                }
                else
                {
                    sequence.Add(Marshal.PtrToStringAnsi(pointer));
                }
            }
        }

19 Source : MarshalHelper.cs
with GNU Lesser General Public License v3.0
from jmmorato

public static void PtrToStringMultiArray(this IntPtr ptr, Array array, bool isUnicode)
    {
        // We need to ensure that the array is not null before the call 
        if (array == null)
            return;

        int elSiz = IntPtr.Size;
        int length = 1;
        for (int i = 0; i < array.Rank; i++)
        {
            length *= array.GetLength(i);
        }

        int[] dimensions = new int[array.Rank];
        int[] dIndex = new int[array.Rank];
        for (int i = 0; i < length; i++)
        {
            if (i > 0)
            {
                UpdateDimensionsArray(array, dimensions);
            }

            // Get the unmanaged pointer
            IntPtr pointer = Marshal.PtrToStructure<IntPtr>(ptr + (IntPtr.Size * i));
            // Convert the pointer in a string
            if (isUnicode)
                array.SetValue(PtrToWideString(pointer), dimensions);
            else
                array.SetValue(Marshal.PtrToStringAnsi(pointer), dimensions);
        }
    }

19 Source : ContentFilteredTopic.cs
with GNU Lesser General Public License v3.0
from jmmorato

private string GetFilterExpression()
        {
            return Marshal.PtrToStringAnsi(UnsafeNativeMethods.GetFilterExpression(_native));
        }

19 Source : TopicBuiltinTopicData.cs
with GNU Lesser General Public License v3.0
from jmmorato

internal void FromNative(TopicBuiltinTopicDataWrapper wrapper)
        {
            Deadline = wrapper.Deadline;
            DestinationOrder = wrapper.DestinationOrder;
            Durability = wrapper.Durability;
            DurabilityService = wrapper.DurabilityService;
            Key = wrapper.Key;
            LatencyBudget = wrapper.LatencyBudget;
            Lifespan = wrapper.Lifespan;
            Liveliness = wrapper.Liveliness;
            Ownership = wrapper.Ownership;
            Reliability = wrapper.Reliability;
            History = wrapper.History;
            ResourceLimits = wrapper.ResourceLimits;
            TransportPriority = wrapper.TransportPriority;

            if (wrapper.Name != IntPtr.Zero)
            {
                Name = Marshal.PtrToStringAnsi(wrapper.Name);
            }
            else
            {
                Name = null;
            }

            if (wrapper.TypeName != IntPtr.Zero)
            {
                TypeName = Marshal.PtrToStringAnsi(wrapper.TypeName);
            }
            else
            {
                TypeName = null;
            }

            if (TopicData == null)
            {
                TopicData = new TopicDataQosPolicy();
            }
            TopicData.FromNative(wrapper.TopicData);
        }

19 Source : ParticipantService.cs
with GNU Lesser General Public License v3.0
from jmmorato

private static string GetDefaultDiscovery()
        {
            IntPtr ptr = UnsafeNativeMethods.NativeGetDefaultDiscovery();

            string defaultDiscovery = Marshal.PtrToStringAnsi(ptr);
            ptr.ReleaseNativePointer();

            return defaultDiscovery;
        }

19 Source : PEOld.cs
with GNU General Public License v3.0
from juliourena

public static PEOld Load(byte[] PEBytes)
        {
            PEOld pe = new PEOld(PEBytes);
            if (pe.Is32BitHeader)
            {
                // Console.WriteLine("Preferred Load Address = {0}", pe.OptionalHeader32.ImageBase.ToString("X4"));
                codebase = PInvoke.Win32.Kernel32.VirtualAlloc(IntPtr.Zero, pe.OptionalHeader32.SizeOfImage, Win32.Kernel32.AllocationType.Commit, Win32.WinNT.PAGE_EXECUTE_READWRITE);
                // Console.WriteLine("Allocated Space For {0} at {1}", pe.OptionalHeader32.SizeOfImage.ToString("X4"), codebase.ToString("X4"));
            }
            else
            {
                // Console.WriteLine("Preferred Load Address = {0}", pe.OptionalHeader64.ImageBase.ToString("X4"));
                codebase = PInvoke.Win32.Kernel32.VirtualAlloc(IntPtr.Zero, pe.OptionalHeader64.SizeOfImage, Win32.Kernel32.AllocationType.Commit, Win32.WinNT.PAGE_EXECUTE_READWRITE);
                // Console.WriteLine("Allocated Space For {0} at {1}", pe.OptionalHeader64.SizeOfImage.ToString("X4"), codebase.ToString("X4"));
            }

            // Copy Sections
            for (int i = 0; i < pe.FileHeader.NumberOfSections; i++)
            {
                IntPtr y = PInvoke.Win32.Kernel32.VirtualAlloc(IntPtrAdd(codebase, (int)pe.ImageSectionHeaders[i].VirtualAddress), pe.ImageSectionHeaders[i].SizeOfRawData, Win32.Kernel32.AllocationType.Commit, Win32.WinNT.PAGE_EXECUTE_READWRITE);
                Marshal.Copy(pe.PEBytes, (int)pe.ImageSectionHeaders[i].PointerToRawData, y, (int)pe.ImageSectionHeaders[i].SizeOfRawData);
                // Console.WriteLine("Section {0}, Copied To {1}", new string(pe.ImageSectionHeaders[i].Name), y.ToString("X4"));
            }

            // Perform Base Relocation
            // Calculate Delta
            IntPtr currentbase = codebase;
            long delta;
            if (pe.Is32BitHeader)
            {
                delta = (int)(currentbase.ToInt32() - (int)pe.OptionalHeader32.ImageBase);
            }
            else
            {
                delta = (long)(currentbase.ToInt64() - (long)pe.OptionalHeader64.ImageBase);
            }
            // Console.WriteLine("Delta = {0}", delta.ToString("X4"));

            // Modify Memory Based On Relocation Table
            IntPtr relocationTable;
            if (pe.Is32BitHeader)
            {
                relocationTable = (IntPtrAdd(codebase, (int)pe.OptionalHeader32.BaseRelocationTable.VirtualAddress));
            }
            else
            {
                relocationTable = (IntPtrAdd(codebase, (int)pe.OptionalHeader64.BaseRelocationTable.VirtualAddress));
            }

            Win32.Kernel32.IMAGE_BASE_RELOCATION relocationEntry = new Win32.Kernel32.IMAGE_BASE_RELOCATION();
            relocationEntry = (Win32.Kernel32.IMAGE_BASE_RELOCATION)Marshal.PtrToStructure(relocationTable, typeof(Win32.Kernel32.IMAGE_BASE_RELOCATION));

            int imageSizeOfBaseRelocation = Marshal.SizeOf(typeof(Win32.Kernel32.IMAGE_BASE_RELOCATION));
            IntPtr nextEntry = relocationTable;
            int sizeofNextBlock = (int)relocationEntry.SizeOfBlock;
            IntPtr offset = relocationTable;

            while (true)
            {
                Win32.Kernel32.IMAGE_BASE_RELOCATION relocationNextEntry = new Win32.Kernel32.IMAGE_BASE_RELOCATION();
                IntPtr x = IntPtrAdd(relocationTable, sizeofNextBlock);
                relocationNextEntry = (Win32.Kernel32.IMAGE_BASE_RELOCATION)Marshal.PtrToStructure(x, typeof(Win32.Kernel32.IMAGE_BASE_RELOCATION));

                IntPtr dest = IntPtrAdd(codebase, (int)relocationEntry.VirtualAdress);

                for (int i = 0; i < (int)((relocationEntry.SizeOfBlock - imageSizeOfBaseRelocation) / 2); i++)
                {
                    IntPtr patchAddr;
                    UInt16 value = (UInt16)Marshal.ReadInt16(offset, 8 + (2 * i));

                    UInt16 type = (UInt16)(value >> 12);
                    UInt16 fixup = (UInt16)(value & 0xfff);

                    switch (type)
                    {
                        case 0x0:
                            break;
                        case 0x3:
                            patchAddr = IntPtrAdd(dest, fixup);
                            //Add Delta To Location.                            
                            int originalx86Addr = Marshal.ReadInt32(patchAddr);
                            Marshal.WriteInt32(patchAddr, originalx86Addr + (int)delta);
                            break;
                        case 0xA:
                            patchAddr = IntPtrAdd(dest, fixup);
                            //Add Delta To Location.
                            long originalAddr = Marshal.ReadInt64(patchAddr);
                            Marshal.WriteInt64(patchAddr, originalAddr + delta);
                            break;
                    }

                }

                offset = IntPtrAdd(relocationTable, sizeofNextBlock);
                sizeofNextBlock += (int)relocationNextEntry.SizeOfBlock;
                relocationEntry = relocationNextEntry;

                nextEntry = IntPtrAdd(nextEntry, sizeofNextBlock);

                if (relocationNextEntry.SizeOfBlock == 0) break;
            }

            // Resolve Imports

            IntPtr z;
            IntPtr oa1;
            int oa2;

            if (pe.Is32BitHeader)
            {
                z = IntPtrAdd(codebase, (int)pe.ImageSectionHeaders[1].VirtualAddress);
                oa1 = IntPtrAdd(codebase, (int)pe.OptionalHeader32.ImportTable.VirtualAddress);
                oa2 = Marshal.ReadInt32(IntPtrAdd(oa1, 16));
            }
            else
            {
                z = IntPtrAdd(codebase, (int)pe.ImageSectionHeaders[1].VirtualAddress);
                oa1 = IntPtrAdd(codebase, (int)pe.OptionalHeader64.ImportTable.VirtualAddress);
                oa2 = Marshal.ReadInt32(IntPtrAdd(oa1, 16));
            }

            // Get And Display Each DLL To Load
            IntPtr threadStart;
            int VirtualAddress, AddressOfEntryPoint, ByteSize;
            if (pe.Is32BitHeader)
            {
                VirtualAddress = (int)pe.OptionalHeader32.ImportTable.VirtualAddress;
                AddressOfEntryPoint = (int)pe.OptionalHeader32.AddressOfEntryPoint;
                ByteSize = 4;
            }
            else
            {
                VirtualAddress = (int)pe.OptionalHeader64.ImportTable.VirtualAddress;
                AddressOfEntryPoint = (int)pe.OptionalHeader64.AddressOfEntryPoint;
                ByteSize = 8;
            }
            int j = 0;
            while (true)
            {
                IntPtr a1 = IntPtrAdd(codebase, (20 * j) + VirtualAddress);
                int entryLength = Marshal.ReadInt32(IntPtrAdd(a1, 16));
                IntPtr a2 = IntPtrAdd(codebase, (int)pe.ImageSectionHeaders[1].VirtualAddress + (entryLength - oa2));
                IntPtr dllNamePTR = (IntPtr)(IntPtrAdd(codebase, Marshal.ReadInt32(IntPtrAdd(a1, 12))));
                string DllName = Marshal.PtrToStringAnsi(dllNamePTR);
                if (DllName == "") { break; }

                IntPtr handle = PInvoke.Win32.Kernel32.LoadLibrary(DllName);
                // Console.WriteLine("Loaded {0}", DllName);
                int k = 0;
                while (true)
                {
                    IntPtr dllFuncNamePTR = (IntPtrAdd(codebase, Marshal.ReadInt32(a2)));
                    string DllFuncName = Marshal.PtrToStringAnsi(IntPtrAdd(dllFuncNamePTR, 2));
                    IntPtr funcAddy = PInvoke.Win32.Kernel32.GetProcAddress(handle, DllFuncName);
                    if (pe.Is32BitHeader) { Marshal.WriteInt32(a2, (int)funcAddy); }
                    else { Marshal.WriteInt64(a2, (long)funcAddy); }
                    a2 = IntPtrAdd(a2, ByteSize);
                    if (DllFuncName == "") break;
                    k++;
                }
                j++;
            }
            // Transfer Control To OEP
            // Call dllmain
            threadStart = IntPtrAdd(codebase, AddressOfEntryPoint);
            DllMain dllmain = (DllMain)Marshal.GetDelegateForFunctionPointer(threadStart, typeof(DllMain));
            dllmain(codebase, 1, IntPtr.Zero);
            // Console.WriteLine("Thread Complete");
            return pe;
        }

19 Source : PEOld.cs
with GNU General Public License v3.0
from juliourena

public IntPtr GetFunctionExport(string funcName)
        {
            IntPtr ExportTablePtr = IntPtr.Zero;
            PEOld.IMAGE_EXPORT_DIRECTORY expDir;

            if (this.Is32BitHeader && this.OptionalHeader32.ExportTable.Size == 0) { return IntPtr.Zero; }
            else if (!this.Is32BitHeader && this.OptionalHeader64.ExportTable.Size == 0) { return IntPtr.Zero; }

            if (this.Is32BitHeader)
            {
                ExportTablePtr = (IntPtr)((ulong)codebase + (ulong)this.OptionalHeader32.ExportTable.VirtualAddress);
            }
            else
            {
                ExportTablePtr = (IntPtr)((ulong)codebase + (ulong)this.OptionalHeader64.ExportTable.VirtualAddress);
            }

            expDir = (PEOld.IMAGE_EXPORT_DIRECTORY)Marshal.PtrToStructure(ExportTablePtr, typeof(PEOld.IMAGE_EXPORT_DIRECTORY));
            for (int i = 0; i < expDir.NumberOfNames; i++)
            {
                IntPtr NameOffsetPtr = (IntPtr)((ulong)codebase + (ulong)expDir.AddressOfNames);
                NameOffsetPtr = (IntPtr)((ulong)NameOffsetPtr + (ulong)(i * Marshal.SizeOf(typeof(uint))));
                IntPtr NamePtr = (IntPtr)((ulong)codebase + (uint)Marshal.PtrToStructure(NameOffsetPtr, typeof(uint)));

                string Name = Marshal.PtrToStringAnsi(NamePtr);
                if (Name.Contains(funcName))
                {
                    IntPtr AddressOfFunctions = (IntPtr)((ulong)codebase + (ulong)expDir.AddressOfFunctions);
                    IntPtr OrdinalRvaPtr = (IntPtr)((ulong)codebase + (ulong)(expDir.AddressOfOrdinals + (i * Marshal.SizeOf(typeof(UInt16)))));
                    UInt16 FuncIndex = (UInt16)Marshal.PtrToStructure(OrdinalRvaPtr, typeof(UInt16));
                    IntPtr FuncOffsetLocation = (IntPtr)((ulong)AddressOfFunctions + (ulong)(FuncIndex * Marshal.SizeOf(typeof(UInt32))));
                    IntPtr FuncLocationInMemory = (IntPtr)((ulong)codebase + (uint)Marshal.PtrToStructure(FuncOffsetLocation, typeof(UInt32)));
                    return FuncLocationInMemory;
                }
            }
            return IntPtr.Zero;
        }

19 Source : Platform.cs
with GNU General Public License v3.0
from junian

static bool IsRunningOnMac ()
		{
			IntPtr buf = IntPtr.Zero;
			try {
				buf = Marshal.AllocHGlobal (8192);
				// This is a hacktastic way of getting sysname from uname ()
				if (uname (buf) == 0) {
					string os = Marshal.PtrToStringAnsi (buf);
					if (os == "Darwin")
						return true;
				}
			} catch {
			} finally {
				if (buf != IntPtr.Zero)
					Marshal.FreeHGlobal (buf);
			}
			return false;
		}

19 Source : CudaHelpers.cs
with MIT License
from kaby76

public static void CheckCudaError(CUresult res)
        {
            if (res.Value != cudaError_enum.CUDA_SUCCESS)
            {
                IntPtr pStr = IntPtr.Zero;
                Functions.cuGetErrorString(res, ref pStr);
                var cuda_error = Marshal.PtrToStringAnsi(pStr);
                throw new Exception("CUDA error: " + cuda_error);
            }
        }

19 Source : Win32.cs
with GNU General Public License v3.0
from Kalejin

public static void DeviceAudit()
        {
            var file = new FileStream("DeviceAudit.txt", FileMode.Create, FileAccess.Write);
            var sw = new StreamWriter(file);

            var keyboardNumber = 0;
            uint deviceCount = 0;
            var dwSize = (Marshal.SizeOf(typeof(Rawinputdevicelist)));

            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                var pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                for (var i = 0; i < deviceCount; i++)
                {
                    uint pcbSize = 0;

                    // On Window 8 64bit when compiling against .Net > 3.5 using .ToInt32 you will generate an arithmetic overflow. Leave as it is for 32bit/64bit applications
                    var rid = (Rawinputdevicelist)Marshal.PtrToStructure(new IntPtr((pRawInputDeviceList.ToInt64() + (dwSize * i))), typeof(Rawinputdevicelist));

                    GetRawInputDeviceInfo(rid.hDevice, RawInputDeviceInfo.RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                    if (pcbSize <= 0)
                    {
                        sw.WriteLine("pcbSize: " + pcbSize);
                        sw.WriteLine(Marshal.GetLastWin32Error());
                        return;
                    }

                    var size = (uint)Marshal.SizeOf(typeof(DeviceInfo));
                    var di = new DeviceInfo {Size = Marshal.SizeOf(typeof (DeviceInfo))};
                    
                    if (GetRawInputDeviceInfo(rid.hDevice, (uint) RawInputDeviceInfo.RIDI_DEVICEINFO, ref di, ref size) <= 0)
                    {
                        sw.WriteLine(Marshal.GetLastWin32Error());
                        return;
                    }
                   
                    var pData = Marshal.AllocHGlobal((int)pcbSize);
                    GetRawInputDeviceInfo(rid.hDevice, RawInputDeviceInfo.RIDI_DEVICENAME, pData, ref pcbSize);
                    var deviceName = Marshal.PtrToStringAnsi(pData);

                    if (rid.dwType == DeviceType.RimTypekeyboard || rid.dwType == DeviceType.RimTypeHid)
                    {
                        var deviceDesc = GetDeviceDescription(deviceName);

                        if (deviceDesc != null)
                        {
                            var dInfo = new KeyPressEvent
                            {
                                DeviceName = Marshal.PtrToStringAnsi(pData),
                                DeviceHandle = rid.hDevice,
                                DeviceType = GetDeviceType(rid.dwType),
                                Name = deviceDesc,
                                Source = keyboardNumber++.ToString(CultureInfo.InvariantCulture)
                            };

                            sw.WriteLine(dInfo.ToString());
                            sw.WriteLine(di.ToString());
                            sw.WriteLine(di.KeyboardInfo.ToString());
                            sw.WriteLine(di.HIDInfo.ToString());
                            //sw.WriteLine(di.MouseInfo.ToString());
                            sw.WriteLine("=========================================================================================================");
                        }
                    }

                    Marshal.FreeHGlobal(pData);
                }

                Marshal.FreeHGlobal(pRawInputDeviceList);

                sw.Flush();
                sw.Close();
                file.Close();

                return;
            }

            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

19 Source : RawKeyboard.cs
with GNU General Public License v3.0
from Kalejin

public void EnumerateDevices()
		{
			lock (_padLock)
			{
				_deviceList.Clear();

				var keyboardNumber = 0;

				var globalDevice = new KeyPressEvent
				{
					DeviceName = "Global Keyboard",
					DeviceHandle = IntPtr.Zero,
					DeviceType = Win32.GetDeviceType(DeviceType.RimTypekeyboard),
					Name = "Fake Keyboard. Some keys (ZOOM, MUTE, VOLUMEUP, VOLUMEDOWN) are sent to rawinput with a handle of zero.",
					Source = keyboardNumber++.ToString(CultureInfo.InvariantCulture)
				};

				_deviceList.Add(globalDevice.DeviceHandle, globalDevice);
				
				var numberOfDevices = 0;
				uint deviceCount = 0;
				var dwSize = (Marshal.SizeOf(typeof(Rawinputdevicelist)));

				if (Win32.GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
				{
					var pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
					Win32.GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

					for (var i = 0; i < deviceCount; i++)
					{
						uint pcbSize = 0;

						// On Window 8 64bit when compiling against .Net > 3.5 using .ToInt32 you will generate an arithmetic overflow. Leave as it is for 32bit/64bit applications
						var rid = (Rawinputdevicelist)Marshal.PtrToStructure(new IntPtr((pRawInputDeviceList.ToInt64() + (dwSize * i))), typeof(Rawinputdevicelist));

						Win32.GetRawInputDeviceInfo(rid.hDevice, RawInputDeviceInfo.RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

						if (pcbSize <= 0) continue;

						var pData = Marshal.AllocHGlobal((int)pcbSize);
						Win32.GetRawInputDeviceInfo(rid.hDevice, RawInputDeviceInfo.RIDI_DEVICENAME, pData, ref pcbSize);
						var deviceName = Marshal.PtrToStringAnsi(pData);

						if (rid.dwType == DeviceType.RimTypekeyboard || rid.dwType == DeviceType.RimTypeHid)
						{
							var deviceDesc = Win32.GetDeviceDescription(deviceName);

							if (deviceDesc != null)
							{
								var dInfo = new KeyPressEvent
								{
									DeviceName = Marshal.PtrToStringAnsi(pData),
									DeviceHandle = rid.hDevice,
									DeviceType = Win32.GetDeviceType(rid.dwType),
									Name = deviceDesc,
									Source = keyboardNumber++.ToString(CultureInfo.InvariantCulture)
								};

								if (!_deviceList.ContainsKey(rid.hDevice))
								{
									numberOfDevices++;
									_deviceList.Add(rid.hDevice, dInfo);
								}
							}
						}

						Marshal.FreeHGlobal(pData);
					}

					Marshal.FreeHGlobal(pRawInputDeviceList);

					NumberOfKeyboards = numberOfDevices;
					Debug.WriteLine("EnumerateDevices() found {0} Keyboard(s)", NumberOfKeyboards);
					return;
				}
			}
			
			throw new Win32Exception(Marshal.GetLastWin32Error());
		}

19 Source : NInchiWrapper.cs
with GNU Lesser General Public License v2.1
from kazuyaujihara

static NInchiOutput ToInchiOutput(int ret, Inchi_Output output)
        {
            var inchi = Marshal.PtrToStringAnsi(output.szInChI);
            var aux = Marshal.PtrToStringAnsi(output.szAuxInfo);
            var mes = Marshal.PtrToStringAnsi(output.szMessage);
            var log = Marshal.PtrToStringAnsi(output.szLog);

            return new NInchiOutput(ret, inchi, aux, mes, log);
        }

19 Source : NInchiWrapper.cs
with GNU Lesser General Public License v2.1
from kazuyaujihara

public static NInchiOutputStructure GetStructureFromInchi(NInchiInputInchi input)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input), "Null input");
            }

            var native_input = new Inchi_InputINCHI();

            var szInChI = Marshal.StringToHGlobalAnsi(input.Inchi);
            var szOptions = Marshal.StringToHGlobalAnsi(input.Options);
            try
            {
                native_input.szInChI = szInChI;
                native_input.szOptions = szOptions;

                var native_output = new Inchi_OutputStruct();

                var ret = GetStructFromINCHI(ref native_input, out native_output);

                NInchiOutputStructure output = new NInchiOutputStructure(ret,
                    Marshal.PtrToStringAnsi(native_output.szMessage),
                    Marshal.PtrToStringAnsi(native_output.szLog),
                    native_output.WarningFlags[0], native_output.WarningFlags[1],
                    native_output.WarningFlags[2], native_output.WarningFlags[3]);

                CreateAtoms(output, native_output.num_atoms, native_output.atom);
                CreateBonds(output, native_output.num_atoms, native_output.atom);
                CreateStereos(output, native_output.num_stereo0D, native_output.stereo0D);

                FreeStructFromINCHI(ref native_output);
                return output;
            }
            finally
            {
                Marshal.FreeHGlobal(szOptions);
                Marshal.FreeHGlobal(szInChI);
            }
        }

19 Source : NInchiWrapper.cs
with GNU Lesser General Public License v2.1
from kazuyaujihara

public static NInchiOutputKey GetInchiKey(string inchi)
        {
            if (inchi == null)
            {
                throw new ArgumentNullException(nameof(inchi), "Null InChI");
            }

            var szINCHIKey = Marshal.AllocHGlobal(28);
            var szXtra1 = Marshal.AllocHGlobal(65);
            var szXtra2 = Marshal.AllocHGlobal(65);
            var ret = GetINCHIKeyFromINCHI(inchi, 1, 2, szINCHIKey, szXtra1, szXtra2);

            NInchiOutputKey oo = new NInchiOutputKey(ret, Marshal.PtrToStringAnsi(szINCHIKey));

            Marshal.FreeHGlobal(szXtra2);
            Marshal.FreeHGlobal(szXtra1);
            Marshal.FreeHGlobal(szINCHIKey);
            return oo;
        }

19 Source : PluginEntry.cs
with MIT License
from keijiro

public static string GetSharedObjectNameString(int index)
        {
            var ptr = GetSharedObjectName(index);
            return ptr != System.IntPtr.Zero ? Marshal.PtrToStringAnsi(ptr) : null;
        }

19 Source : PluginEntry.cs
with MIT License
from keijiro

public static string SearchSharedObjectNameString(string keyword)
        {
            var ptr = SearchSharedObjectName(keyword);
            return ptr != System.IntPtr.Zero ? Marshal.PtrToStringAnsi(ptr) : null;
        }

19 Source : TimeProfile.cs
with BSD 2-Clause "Simplified" License
from keijiro

unsafe string ConvertName()
    {
        fixed (byte* p = name) return Marshal.PtrToStringAnsi((IntPtr)p);
    }

19 Source : TinyFileDialog.cs
with MIT License
from KillzXGaming

private static string stringFromAnsi(IntPtr ptr)
        {
            return Marshal.PtrToStringAnsi(ptr);
        }

19 Source : Introspect.cs
with MIT License
from kleisauke

private IEnumerable<KeyValuePair<string, Enums.ArgumentFlags>> GetArgs(Operation operation)
        {
            var args = new List<KeyValuePair<string, Enums.ArgumentFlags>>();

            void AddArg(string name, Enums.ArgumentFlags flags)
            {
                // libvips uses '-' to separate parts of arg names, but we
                // need '_' for C#
                name = name.Replace("-", "_");

                args.Add(new KeyValuePair<string, Enums.ArgumentFlags>(name, flags));
            }

            // vips_object_get_args was added in 8.7
            if (NetVips.AtLeastLibvips(8, 7))
            {
                var result = Internal.VipsObject.GetArgs(operation, out var names, out var flags, out var nArgs);

                if (result != 0)
                {
                    throw new VipsException("unable to get arguments from operation");
                }

                for (var i = 0; i < nArgs; i++)
                {
                    var flag = (Enums.ArgumentFlags)Marshal.PtrToStructure(flags + i * sizeof(int), typeof(int));
                    if ((flag & Enums.ArgumentFlags.CONSTRUCT) == 0)
                    {
                        continue;
                    }

                    var name = Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(names, i * IntPtr.Size));

                    AddArg(name, flag);
                }
            }
            else
            {
                IntPtr AddConstruct(IntPtr self, IntPtr pspec, IntPtr argumentClreplaced, IntPtr argumentInstance,
                    IntPtr a,
                    IntPtr b)
                {
                    var flags = argumentClreplaced.Dereference<VipsArgumentClreplaced>().Flags;
                    if ((flags & Enums.ArgumentFlags.CONSTRUCT) == 0)
                    {
                        return IntPtr.Zero;
                    }

                    var name = Marshal.PtrToStringAnsi(pspec.Dereference<GParamSpec.Struct>().Name);

                    AddArg(name, flags);

                    return IntPtr.Zero;
                }

                Vips.ArgumentMap(operation, AddConstruct, IntPtr.Zero, IntPtr.Zero);
            }

            return args;
        }

19 Source : NetVips.cs
with MIT License
from kleisauke

public static string[] GetSuffixes()
        {
            if (!AtLeastLibvips(8, 8))
            {
                return null;
            }

            var ptrArr = VipsForeign.GetSuffixes();

            var names = new List<string>();

            var count = 0;
            IntPtr strPtr;
            while ((strPtr = Marshal.ReadIntPtr(ptrArr, count * IntPtr.Size)) != IntPtr.Zero)
            {
                var name = Marshal.PtrToStringAnsi(strPtr);
                names.Add(name);
                GLib.GFree(strPtr);
                ++count;
            }

            GLib.GFree(ptrArr);

            return names.ToArray();
        }

See More Examples