21xrx.com
2024-11-22 07:19:34 Friday
登录
文章检索 我的文章 写文章
C++读写内存的源代码
2023-07-13 00:11:55 深夜i     --     --
C++ 读写 内存 源代码

C++作为一门底层编程语言,可以直接读写内存,这对于需要高性能的程序非常有用。下面是C++读写内存的源代码。

读取内存:


// 读取一块内存

void* MemRead(const void* address, size_t size) {

  void* buffer = malloc(size);

  memcpy(buffer, address, size);

  return buffer;

}

// 读取一个未知大小的整数(注意字节序)

int ReadUnknownInt(const void* address) {

  uint8_t firstByte = *(uint8_t*)address;

  if (firstByte < 0x80)

    return firstByte;

  

  if (firstByte < 0xC0) {

    uint16_t value = (firstByte - 0x80) << 8;

    value |= *(uint8_t*)(address + 1);

    return value;

  }

  if (firstByte < 0xE0) {

    uint32_t value = (firstByte - 0xC0) << 24;

    value |= *(uint8_t*)(address + 1) << 16;

    value |= *(uint8_t*)(address + 2) << 8;

    value |= *(uint8_t*)(address + 3);

    return value;

  }

  if (firstByte < 0xF0) {

    uint64_t value = (firstByte - 0xE0ull) << 56;

    value |= (uint64_t)*(uint8_t*)(address + 1) << 48;

    value |= (uint64_t)*(uint8_t*)(address + 2) << 40;

    value |= (uint64_t)*(uint8_t*)(address + 3) << 32;

    value |= (uint64_t)*(uint8_t*)(address + 4) << 24;

    value |= (uint64_t)*(uint8_t*)(address + 5) << 16;

    value |= (uint64_t)*(uint8_t*)(address + 6) << 8;

    value |= (uint64_t)*(uint8_t*)(address + 7);

    return (int)value;

  }

  return 0;

}

写入内存:


// 将一块内存写入另一块内存

void MemWrite(void* destination, const void* source, size_t size) {

  memcpy(destination, source, size);

}

// 写入一个未知大小的整数(注意字节序)

void WriteUnknownInt(int value, void* address) {

  if (value >= -0x80 && value < 0x80) {

    *(uint8_t*)address = (uint8_t)value;

  } else if (value >= -0x4000 && value < 0x4000) {

    *(uint8_t*)address = 0x80 + (uint8_t)(value >> 8);

    *(uint8_t*)(address + 1) = (uint8_t)value;

  } else if (value >= -0x200000 && value < 0x200000) {

    *(uint8_t*)address = 0xC0 + (uint8_t)(value >> 24);

    *(uint8_t*)(address + 1) = (uint8_t)(value >> 16);

    *(uint8_t*)(address + 2) = (uint8_t)(value >> 8);

    *(uint8_t*)(address + 3) = (uint8_t)value;

  } else if (value >= -0x100000000ll && value < 0x100000000ll) {

    *(uint8_t*)address = 0xE0 + (uint8_t)(value >> 56);

    *(uint8_t*)(address + 1) = (uint8_t)(value >> 48);

    *(uint8_t*)(address + 2) = (uint8_t)(value >> 40);

    *(uint8_t*)(address + 3) = (uint8_t)(value >> 32);

    *(uint8_t*)(address + 4) = (uint8_t)(value >> 24);

    *(uint8_t*)(address + 5) = (uint8_t)(value >> 16);

    *(uint8_t*)(address + 6) = (uint8_t)(value >> 8);

    *(uint8_t*)(address + 7) = (uint8_t)value;

  }

}

这些函数可以帮助开发人员直接读写内存,如读取程序中某个变量的值,或将指定内存块中的数据写回磁盘。这些功能虽然强大,但也不宜滥用,因为读写内存实际上破坏了程序的内部状态,可能导致程序崩溃或运行不正常。因此,开发人员需要仔细地设计和测试代码,避免出现不可预测的错误。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复