【问题标题】:Cast void pointer to uint64_t array in C将 void 指针转换为 C 中的 uint64_t 数组
【发布时间】:2013-03-08 11:04:53
【问题描述】:

我目前正在使用 Linux 内核模块,我需要访问一些存储在数组中的 64 位值,但是我首先需要从 void 指针进行转换。

我正在使用返回 void 指针的内核函数 phys_to_virt,但我不完全确定如何实际使用此 void 指针来访问它指向的数组中的元素。

目前我正在这样做:

void *ptr;
uint64_t test;

ptr = phys_to_virt(physAddr);
test = *(uint64_t*)ptr;
printk("Test: %llx\n", test);

我从测试中得到的值不是我期望在数组中看到的,所以我很确定我做错了什么。我需要访问数组中的前三个元素,因此我需要将 void 指针转换为 uint64_t[] 但我不太确定如何执行此操作。

任何建议将不胜感激。

谢谢

【问题讨论】:

  • 代码本身似乎是有效的,但是将物理内存映射到虚拟内存并不是在所有情况下都是有效的操作。你的physAddr 到底指的是什么?
  • 它应该指向一个包含 64 位长值的 512 元素数组。
  • 但是这个数组是什么?是否在外部设备的共享内存中?
  • 演员阵容很好,问题肯定出在其他地方。
  • 您也可以使用uint64_t * ptest = (uint64_t*)ptr; printk("Test: %llx\n", ptest[0]); 来获取数组的第一个元素。那么第二个元素的代码很明显,不是吗? ;-)

标签: c pointers memory void-pointers dereference


【解决方案1】:

我正在使用返回 void 指针的内核函数 phys_to_virt,但我不完全确定如何实际使用此 void 指针来访问它指向的数组中的元素。

是的,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];

您可能会发现它更清楚一些,并且意思相同。

【讨论】:

    猜你喜欢
    • 2012-11-21
    • 1970-01-01
    • 2011-07-31
    • 2021-09-20
    • 2013-01-19
    • 1970-01-01
    • 2016-01-12
    • 2010-12-14
    相关资源
    最近更新 更多