简体   繁体   English

如何从C中的“原始”内存中读取/写入类型值?

[英]How to read/write type values from “raw” memory in C?

How do I make something like this work? 我如何制作这样的作品呢?

void *memory = malloc(1000);  //allocate a pool of memory
*(memory+10) = 1;  //set an integer value at byte 10
int i = *(memory+10);  //read an integer value from the 10th byte

Easy example: treat the memory as an array of unsigned char 简单示例:将内存视为unsigned char数组

void *memory = malloc(1000);  //allocate a pool of memory
uint8_t *ptr = memory+10;  
*ptr = 1 //set an integer value at byte 10
uint8_t i = *ptr;  //read an integer value from the 10th byte

You can use integers too, but then you must pay attention about the amount of bytes you are setting at once. 您也可以使用整数,但是您必须注意一次设置的字节数。

The rules are simple: 规则很简单:

  • every pointer type (except function pointers) can be cast to and from void*, without loss. 每个指针类型(函数指针除外)都可以转换为void *,而不会丢失。
  • you cannot perform pointer arithmetic on void* pointers, and cannot dereference them 你不能对void *指针执行指针运算,也不能取消引用它们
  • sizeof(char) equals 1, by definition; 根据定义,sizeof(char)等于1; so incrementing a char pointer means "adding 1" to the "raw" pointer value 所以递增一个字符指针意味着“添加1”到“原始”指针值

From this you can conclude that if you want to perform "raw" pointer arithmetic you have to cast to and from char*. 由此可以得出结论,如果要执行“原始”指针算法,则必须转换为char *。

So, by "work" I assume you mean "how do I dereference/perform pointer arithmetic on a void* "? 所以,通过“工作”,我假设你的意思是“如何取消引用/执行void*指针算术void* ”? You can't; 你不能; you have to cast it, typically to a char* if you're just concerned with reading chunks of memory. 如果你只是关心阅读大块的内存,你必须把它强制转换为char* Of course, if that's the case, simply declare it as a char* to begin with. 当然,如果是这种情况,只需将其声明为char*即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM