I'm currently working with a Linux kernel module and I need to access some 64-bit values stored in an array, however I first need to cast from a void pointer.
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.
Currently I'm doing this:
void *ptr;
uint64_t test;
ptr = phys_to_virt(physAddr);
test = *(uint64_t*)ptr;
printk("Test: %llx\n", test);
The value I'm getting from test isn't what I expected to see within the array, so I'm fairly sure I'm doing something wrong. I need to access the first three elements in the array, so I need to cast the void pointer to a uint64_t[] but I'm not quite sure how to do that.
Any advice would be greatly appreciated.
Thanks
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.
Yup, phys_to_virt()
does indeed return a void *
. The concept of the void *
is that it's typeless, so you can store anything to it, and yes you need to typecast it to something to extract information from it.
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.
So yes, test = *(uint64_t*)ptr;
will correctly typecast and give you the first element of the array. Note you can also write it like this:
test = ((uint64_t *)ptr)[0];
Which you might find a little bit clearer and means the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With