Reputation: 1525
I'm writing a module for Linux kernel, and I want to store a int
value in the file private data.
Essentially, what I do is: file->private_data = (void*) x
where x is some int
value.
Now, I want to access the int back as a value.
Using int val = (int) file->private_data
gives out a cast from pointer to integer of different size
warning during compilation, which is reasonable since it may cause problems on a 64bit systems.
I also cannot use uintptr_t
since I'm working in kernel and I do not have access to libraries.
Using double
seems inappropriate.
My question is: What should be the best practice to do so?
Upvotes: 3
Views: 2092
Reputation:
Can you please elaborate how come you got yourself into a situation where storing an int there is reasonable?
Normally this would be a pointer to a reference-counted object. In particular, if you are using that to look up another object, this very field should probably just point to that object.
Upvotes: 0
Reputation: 66118
In gcc world (Linux kernel is compiled by gcc), long
(or unsigned long
) has the the same size as a pointer. You may use this feature when convert pointers to integer and back:
// store
file->private_data = (void*)(long) x;
// load
int val = (int) (long) file->private_data;
Note: This answer addresses specifically Linux kernel programming.
For user-space application suggested approach could be treated as a bad practice, or simply being wrong.
Upvotes: 5