modify function to read float C#

被刻印的时光 ゝ 提交于 2019-12-12 00:33:41

问题


I found this function on the internet:

[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(IntPtr hProcess, int lpBaseAddress, byte[] buffer, int size, int lpNumberOfBytesRead);



    public static int ReadAddress(string Process_Name, string Address_Offsets)
    {
        Process[] P;
        if ((P = Process.GetProcessesByName(Process_Name)).Length == 0) return -1;
        int Addy = -1;
        while (Address_Offsets.Contains("  "))
            Address_Offsets = Address_Offsets.Replace("  ", " ");

        int Index = -1;
        while ((Index = Address_Offsets.IndexOf("0x", StringComparison.OrdinalIgnoreCase)) != -1)
            Address_Offsets = Address_Offsets.Replace(Address_Offsets.Substring(Index, 2), "");

        string[] tmp = Address_Offsets.Split(' ');
        if (tmp[0].Contains("+"))
        {
            string[] AD = tmp[0].Split('+');
            foreach (ProcessModule M in P[0].Modules)
                if (M.ModuleName.ToLower() == AD[0].ToLower())
                    Addy = M.BaseAddress.ToInt32() + int.Parse(AD[1], NumberStyles.HexNumber);
        }
        else Addy = int.Parse(tmp[0], NumberStyles.HexNumber);

        if (tmp.Length == 1) return Addy;
        byte[] buff = new byte[4];
        ReadProcessMemory(P[0].Handle, Addy, buff, 4, 0);
        Addy = BitConverter.ToInt32(buff, 0);
        for (int i = 1; i < tmp.Length; i++)
        {
            int Off = int.Parse(tmp[i], NumberStyles.HexNumber);
            ReadProcessMemory(P[0].Handle, Addy + Off, buff, 4, 0);
            Addy = i != (tmp.Length - 1) ? BitConverter.ToInt32(buff, 0) : Addy += Off;
        }
        return Addy;
    }

I is used like:

ReadAddress("solitaire", "solitaire.exe+97074 2c 10");

This function works good for reading integers. But I want to read floats. Someone told me, that I have to do

ReadProcessMemory(P[0].Handle, Addy, buff, 4, 0); // after you dereference all pointers and get the final "desired" value. 
Addy = BitConverter.ToSingle(buff, 0); // ToSingle converts value to float.

But I do not understand where to put his suggested code in the function. Can someone help me pls? thx in advance :D.


回答1:


int dataRead = ReadAddress("solitaire", "solitaire.exe+97074 2c 10");

Gives you (hopefully) 4 bytes in an int.

After you've read this int, you need to convert it to float, which means

byte[] bytesOfTheNumber = BitConverter.GetBytes(dataRead);

converting the integer number into a byte array first, and then

float theFloatYouWant = BitConverter.ToSingle(bytesOfTheNumber, 0);

using that byte array for getting a float.



来源:https://stackoverflow.com/questions/30694922/modify-function-to-read-float-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!