指针传参hack
c语言中有时会看到 void * data 这样的类型,可以通过cast转换为任意需要的数据指针。C语言中的pointer一般为 4 Bytes 也即 32 位。当传递的参数不大时,完全可以把一个int塞进这个指针中传递,从而省下了申请内存的麻烦。
一个常见的例子是,在GUI编程中为按钮绑定点击事件。
|
|
其中
|
|
为按钮绑定一个点击事件func
,假设func
需要接受一个整数参数,这里可以这样写
|
|
可以强行把一个整数塞进指针的32位存储空间中。但注意一般整数为64位,这样做有可能导致溢出。
解决办法是:使用 intptr_t
类型,它在stdint.h
中。这个类型其实就是32位的整数。对应地,可以这样:
|
|
[+] 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 <<