字符串的内存地址

时间:2015-06-25 11:07:22

标签: c# memory

我有写内存的功能,但是我想从字符串中导入地址,怎么做? 代码:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(int hProcess, int lpBaseAddress,
byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesWritten);

和此:

WriteProcessMemory((int)processHandle, 0xffffffff, buffer, buffer.Length, ref bytesWritten);

我想将此"0xffffffff"替换为string,但我不知道如何执行此操作。我尝试将带地址的字符串转换为int,但这不起作用。

1 个答案:

答案 0 :(得分:3)

使用类似:

string str = "0xffffffffffffffff";
if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
    str = str.Substring(2);
}
IntPtr ptr = (IntPtr)long.Parse(str, NumberStyles.HexNumber);

请注意,long.Parse不支持0x,因此如果存在,我会将其删除。

我使用long.Parse来支持64位系统和32位系统。

请注意,您使用的PInvoke签名是错误的...它将适用于32位,但是通常兼容32位和64位的是:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(
    IntPtr hProcess, 
    IntPtr lpBaseAddress, 
    byte[] lpBuffer, 
    IntPtr dwSize, 
    out IntPtr lpNumberOfBytesWritten);

如果您需要操纵IntPtr,则应始终将其转换为long,因为IntPtr可以是32位或64位,因此long始终可以包含#!/bin/bash value="Maria Ion Gheorghe Vasile Maria Maria Ion Vasile Gheorghe" value2="Maria Ion Gheorghe Vasile Maria Maria Ion Vasile Gheorghe" if [[ "$value"!="$value2" ]]; then echo "different" else echo "match" fi