强制转换为整数的指针在64位拱上发出警告 [英] casting a pointer to integer issues warning on 64bit arch

查看:115
本文介绍了强制转换为整数的指针在64位拱上发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用导出符号open_exec

I'm writing a linux kernel module that makes use of the exported symbol open_exec

struct file *open_exec(const char *name)

它返回一个指针,我可以使用IS_ERR宏检查错误:

It returns a pointer, and I can check for an error with the IS_ERR macro:

if (IS_ERR(file))
    return file;

在编译期间,我收到以下警告:

During compile time, I get this warning:

warning: return makes integer from pointer without a cast

这是因为我的函数在这里返回一个整数.如果我尝试投射它:

This is because my function here returns an integer. If I try to cast it:

return (int) file;

我在32位计算机上没有收到警告,但在64位计算机上却得到了警告:

I don't get a warning on my 32bit machine, but I do on my 64bit machine:

warning: cast from pointer to integer of different size

这是因为int和指针的sizeof在32位上相同,但是在64位计算机上却不同.

This is because the sizeof of an int and a pointer are the same on 32bit, but they differ on a 64bit machine.

无论是否进行铸造,该代码似乎都可以正常工作.我想摆脱警告.

Casting it or not, the code appears to work. I'd just like to get rid of the warning.

我如何正确地将指针转换为整数并获得我期望的值,而又没有得到编译器警告?我期望的值本质上是Linux内核代码库的include/asm-generic/errno-base.h中列出的整数.

How do I properly cast a pointer to an integer and get the value I expect, while not getting a compiler warning? The value I expect is essentially an integer listed in include/asm-generic/errno-base.h of the linux kernel code base.

由于在IS_ERR()为true的情况下,我仅将指针视为整数,因此我可以确定实际上它仅保留整数值.

Since I'm only looking at the pointer as if it was an integer in the case where IS_ERR() is true, I can be sure that it does in-fact only hold an integer value.

推荐答案

linux/err.h中的PTR_ERR()宏(也定义了IS_ERR())将实际上是错误代码的指针转换为适当的类型(一个long).

The PTR_ERR() macro in linux/err.h, which is where IS_ERR() is also defined, converts a pointer that's really an error code into the appropriate type (a long).

您应使用类似以下内容的

You should use something like:

if (IS_ERR(file))
    return PTR_ERR(file);

在源代码中搜索PTR_ERR()的现有用法,您会发现这是一种常见的模式.

Search for existing uses of PTR_ERR() in the source and you'll see this is a common pattern.

对于您的函数来说,返回long而不是int可能是合适的-但所有错误代码都应在int中表示.

It might be appropriate for your function to return a long rather than an int - but all error codes should be representable in an int.

这篇关于强制转换为整数的指针在64位拱上发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆