[英]C - best practice for casting a void* to int, kernel
I'm writing a module for Linux kernel, and I want to store a int
value in the file private data. 我正在为Linux内核编写模块,并且想在文件私有数据中存储一个
int
值。
Essentially, what I do is: file->private_data = (void*) x
where x is some int
value. 本质上,我要做的是:
file->private_data = (void*) x
其中x是一些int
值。
Now, I want to access the int back as a value. 现在,我想将int作为值进行访问。
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. 使用
int val = (int) file->private_data
会在编译期间给出cast from pointer to integer of different size
警告,这是合理的,因为这可能会在64位系统上引起问题。
I also cannot use uintptr_t
since I'm working in kernel and I do not have access to libraries. 我也不能使用
uintptr_t
因为我正在内核中工作,而且无法访问库。
Using double
seems inappropriate. 使用
double
似乎不合适。
My question is: What should be the best practice to do so? 我的问题是:最佳做法是什么?
In gcc world (Linux kernel is compiled by gcc), long
(or unsigned long
) has the the same size as a pointer. 在gcc世界(Linux内核由gcc编译)中,
long
(或unsigned long
)具有与指针相同的大小。 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. 注意 :此答案专门针对Linux内核编程。
For user-space application suggested approach could be treated as a bad practice , or simply being wrong . 对于用户空间应用程序,建议的方法可能被视为不好的做法 ,或者仅仅是错误的 做法 。
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.
特别是,如果您使用它来查找另一个对象,则该字段可能应该仅指向该对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.