使用 XtPointer 传递 int 安全吗?
在 Xt 中定义回调过程(例如 XtTimerCallbackProc
)时,client_data
被指定为 XtPointer
。通过 client_data
传递 int
(而不是实际的指针)并将其强制转换回过程内是否安全?
例如:
void foo(void) {
...
int data = 1;
XtAppAddTimeout(app_context, 1000, timer_cb, data);
...
}
void timer_cb(XtPointer client_data, XtIntervalId *timer)
{
int my_data = (int) client_data;
...
}
When defining a callback proc in Xt (for example XtTimerCallbackProc
), client_data
is specified as an XtPointer
. Is it safe to pass an int
via client_data
, rather than an actual pointer, and cast it back inside the procedure?
For example:
void foo(void) {
...
int data = 1;
XtAppAddTimeout(app_context, 1000, timer_cb, data);
...
}
void timer_cb(XtPointer client_data, XtIntervalId *timer)
{
int my_data = (int) client_data;
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的; API 使用指针,因为该类型的大小 >= 几乎所有计算机/编译器组合上 int 的大小,因此您可以使用它通过简单地转换来传递除
double
之外的大多数内容。Yes; the API uses a pointer because the size of this type is >= the size of an int on almost any computer/compiler combination, so you can use it to pass most things except
double
simply by casting.它应该是安全的,但您应该使用与指针大小相同的整数类型。
标准 C99 类型 uintptr_t 可用于此目的。
根据注释指出,使用此类型不能保证 int->ptr->int 。它应该比经常工作,但它不符合规范。
另一种方法是传递指针。如果你的应用程序是单线程的,你可能只需要
静态 int 数据;并传递数据。如果您的应用程序需要可重入,则 malloc 一个 int。
事实上,我认为标准不以任何方式支持 int->ptr->int 。
It should be safe, but you should use an integer type that have the same size as a pointer.
The standard C99 type uintptr_t can be used for this purpose.
As per comments point out, int->ptr->int is not guaranteed by the use of this type. It should work more than often, but it is not as per specifications.
The alternative is to pass a pointer. If your app is single threaded, you might just do
static int data; and passs &data. If your app needs to be reentrant, then malloc an int.
As a matter of fact, I don't think the standard support int->ptr->int in any way.
当我尝试在 64 位 Linux - Redhat 9 上编译 Motiftoggle_box.c 示例时,我遇到了这个问题。
示例代码将
int
作为XtPointer client_data
传递回调函数的参数。g++ 编译器抱怨精度损失,而我似乎没有得到正确的值。
我更改了创建小部件的代码,将
int i;
更改为unsigned long i;
:然后我更改了
toggled()
回调的声明子程序来反映这一点:这对我有用。
I ran into this issue when trying to compile the Motif toggle_box.c example on a 64-bit Linux - Redhat 9.
The example code was passing an
int
as theXtPointer client_data
parameter of a callback function.The g++ compiler complained about loss of precision and I didn't seem to be getting the correct values.
I changed the code creating the widgets, changing
int i;
tounsigned long i;
:I then changed the declaration of the
toggled()
callback subroutine to reflect this:This worked for me.