process_create()としてパラメータを持つ関数がありvoid*ます。を渡したい場合int、コンパイラからのビルドエラーを回避するにはどうすればよいですか? パラメータリストを次のように変更できませんprocess_create()
2 に答える
To be safe, you can cast your integer to intptr_t, which is guaranteed to be the same size as a pointer, and back.
#include <inttypes.h>
inline void *int_to_ptr(int n) {
return (void *) (intptr_t) n;
}
inline int ptr_to_int(void *p) {
return (int) (intptr_t) p;
}
Use int_to_ptr when calling process_create, and ptr_to_int when converting back.
This is still technically not portable ISO C, because:
While it is guaranteed that an arbitrary pointer will survive a roundtrip to
intptr_tand back, it is undefined behavior to even create a pointer from anintptr_tvalue like does not correspond to a valid pointer, such as 1. In theory, the implementation might choke on the invalid pointer, or the integer value might not survive the roundtrip fromintptr_tto pointer and back.In theory, some C implementation could have
intwider than pointers, in which case some valid integer values will overflow in the case tointptr_t.
Both of these cases are highly unlikely to be encountered in practice. C code in widely deployed and portable software uses casts like the above for this purpose.
intを toにキャストすることもできますがvoid*、移植性はありません。たとえば、可能性は低いですが、sizeof(int)>sizeof(void*). したがって、移植可能にしたい場合は、へのポインターを渡す必要がありますint。
たとえば、 でストレージを割り当てることができintますmalloc。
int *myparam = malloc(sizeof(*myparam));
*myparam = 42;
process_create(myparam);
何が何であり、何を行うのかをもっと知らなければ、そのメモリ ブロックをprocess_create呼び出す責任を誰が負うべきかはわかりません。free
ここでの私の仮定は、それは非同期であり、への呼び出しが返さprocess_createれた後しばらくしてポインターを読み取ることができるということです。process_createただし、実行中にポインターが読み取られる場合は、process_createさらに簡単にすることができます。
int myparam = 42;
process_create(&myparam);
int*つまり、要点は、 toを渡すのが最善だと思うということprocess_createです。それをどのように実現するかは、 の操作によって異なりますprocess_create。