指针传参hack

c语言中有时会看到 void * data 这样的类型,可以通过cast转换为任意需要的数据指针。C语言中的pointer一般为 4 Bytes 也即 32 位。当传递的参数不大时,完全可以把一个int塞进这个指针中传递,从而省下了申请内存的麻烦。

一个常见的例子是,在GUI编程中为按钮绑定点击事件。

1
Widget MakeButton(char *label, ButtonCB function, void *data);

其中

1
typedef void (*ButtonCB)(Widget w, void *data);

为按钮绑定一个点击事件func,假设func需要接受一个整数参数,这里可以这样写

1
2
3
4
5
void func(void *data){
    int x = (int) data;

    // TODO
}

可以强行把一个整数塞进指针的32位存储空间中。但注意一般整数为64位,这样做有可能导致溢出。

解决办法是:使用 intptr_t 类型,它在stdint.h中。这个类型其实就是32位的整数。对应地,可以这样:

1
intptr_t x = (intptr_t)data;
#C
Jul 9, 2019


[+] click to leave a comment [+]
the comment system on this blog works via email. The button
below will generate a mailto: link based on this page's url 
and invoke your email client - please edit the comment there!

[optional] even better, encrypt the email with my public key

- don't modify the subject field
- specify a nickname, otherwise your comment will be shown as   
  anonymous
- your email address will not be disclosed
- you agree that the comment is to be made public.
- to take down a comment, send the request via email.

>> SEND COMMENT <<




Voice? via Blog on luis.zip January 12, 2024

Who is the voice inside my head? I have a voice in my mind. I’m hearing it now. It dictates what I write. Sometimes when I think about something, it speaks to me as if it were not me, as if it were not a product of the imagination that belongs to my domain…

2023 in Books via Wesley's Notebook January 7, 2024

recently ~ august23 via Sindre Kjelsrud September 5, 2023

what i've been doing during the month of august.

Generated by openring from webring