加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中将void void指针转换为uint64_t数组

发布时间:2020-12-16 05:02:56 所属栏目:百科 来源:网络整理
导读:我目前正在使用 Linux内核模块,我需要访问存储在数组中的一些64位值,但是我首先需要从void指针进行转换. 我正在使用返回void指针的内核函数phys_to_virt,我不完全确定如何实际使用此void指针来访问它指向的数组中的元素. 目前我这样做: void *ptr;uint64_t
我目前正在使用 Linux内核模块,我需要访问存储在数组中的一些64位值,但是我首先需要从void指针进行转换.

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

目前我这样做:

void *ptr;
uint64_t test;

ptr = phys_to_virt(physAddr);
test = *(uint64_t*)ptr;
printk("Test: %llxn",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 *的概念是它是无类型的,所以你可以存储任何东西,是的,你需要将其类型化以从中提取信息.

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];

您可能会发现哪些更清晰,意味着同样的事情.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读