我目前正在使用 Linux 内核模块,我需要访问存储在数组中的一些 64 位值,但是我首先需要从一个空指针进行转换。
我正在使用返回一个空指针的内核函数 phys_to_virt
,但我不完全确定如何实际使用这个空指针来访问它指向的数组中的元素。
目前我正在这样做:
void *ptr;
uint64_t test;
ptr = phys_to_virt(physAddr);
test = *(uint64_t*)ptr;
printk("Test: %llx\n", test);
我从测试中得到的值不是我期望在数组中看到的值,所以我很确定我做错了什么。我需要访问数组中的前三个元素,因此我需要将 void 指针转换为 uint64_t[],但我不太确定该怎么做。
如有任何建议,我们将不胜感激。
谢谢
最佳答案
I'm using the kernel function phys_to_virt which is returning a void pointer, and I'm not entirely sure how to actually use this void pointer to access elements within the array that it points to.
是的,phys_to_virt()
确实返回一个 void *
。 void *
的概念是它是无类型的,因此您可以向其中存储任何内容,是的,您需要将其类型转换为某种内容以从中提取信息。
ptr = phys_to_virt(physAddr); // void * returned and saved to a void *, that's fine
test = *(uint64_t*)ptr; // so: (uint64_t*)ptr is a typecast saying "ptr is now a
// uint64_t pointer", no issues there
// adding the "*" to the front deferences the pointer, and
// deferencing a pointer (decayed from an array) gives you the
// first element of it.
是的,test = *(uint64_t*)ptr;
将正确进行类型转换并为您提供数组的第一个元素。注意你也可以这样写:
test = ((uint64_t *)ptr)[0];
你可能会觉得更清楚一点,意思是一样的。
关于在 C 中将 void 指针转换为 uint64_t 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15505154/