C - 将void *转换为int,kernel的最佳实践

时间:2022-09-01 10:14:06

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在编译期间给出从指针到不同大小警告的整数的强制转换,这是合理的,因为它可能在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?

我的问题是:这样做的最佳做法是什么?

2 个解决方案

#1


3  

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:

在gcc世界中(Linux内核由gcc编译),long(或unsigned long)具有与指针相同的大小。将指针转换为整数和后退时,可以使用此功能:

// 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.

对于用户空间应用程序,建议的方法可以被视为一种不好的做法,或者只是错误的做法。

#2


0  

Can you please elaborate how come you got yourself into a situation where storing an int there is reasonable?

你能详细说明你是如何进入存储合理的int的情况的吗?

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.

通常,这将是指向引用计数对象的指针。特别是,如果您使用它来查找另一个对象,那么这个字段应该只指向该对象。

#1


3  

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:

在gcc世界中(Linux内核由gcc编译),long(或unsigned long)具有与指针相同的大小。将指针转换为整数和后退时,可以使用此功能:

// 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.

对于用户空间应用程序,建议的方法可以被视为一种不好的做法,或者只是错误的做法。

#2


0  

Can you please elaborate how come you got yourself into a situation where storing an int there is reasonable?

你能详细说明你是如何进入存储合理的int的情况的吗?

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.

通常,这将是指向引用计数对象的指针。特别是,如果您使用它来查找另一个对象,那么这个字段应该只指向该对象。