reinterpret_castは、参照先の型が異なるポインタ間、またはポインタと変数の間でのキャスト、などに使われるC++のキャスト演算子のひとつ・・・。
char *とunsigned int *間でキャストしてみる・・・。
また、char *とunsigned int間でも試してみる・・・。
要素数5のchar型動的配列のポインタをch_ptrに入れ、それに"abcd"をstrcpy・・・。
同じポインタでも参照先が違う型だと、暗黙の型変換の対象にならない・・・。
C言語キャストで無理矢理キャストすることはできるが、そうするとstatic_castな時と区別が付かないので、reinterpret_castを使う・・・。
ポインタは32bit環境なら4バイト、unsigned intも4バイトなので、unsigned intへのキャストもできる・・・。
(VBでLongにポインタを入れたり、HANDLEとポインタのキャストなど、ポインタと変数のキャストも結構ある・・・。)
ch_ptrの参照先を文字列、バイト列として出力・・・。
ui_ptr, ui_ptr2の参照先を16進整数値として出力・・・。
ch_ptrそのものの値、uiの値を出力・・・。
ただし、このままコンパイルすると、
$ vi reinterpret_cast.cpp $ g++ reinterpret_cast.cpp -o reinterpret_cast reinterpret_cast.cpp: 関数 ‘int main()’ 内: reinterpret_cast.cpp:24:45: エラー: cast from ‘char*’ to ‘unsigned int’ loses precision [-fpermissive] ui = reinterpret_cast<unsigned int>(ch_ptr); // reinterpret_castでunsigned intにキャスト. ^ $
64bitでコンパイルしているとchar *が8バイトなのでこうなるので、
$ g++ reinterpret_cast.cpp -o reinterpret_cast -m32 $ ./reinterpret_cast ch_ptr = abcd ch_ptr = 61626364 ui_ptr = 64636261 ui_ptr2 = 64636261 ch_ptr = 09a01008 ui = 09a01008 $
-m32をつけて32bitでコンパイルして実行・・・。
ch_ptrとui_ptrはリトルエンディアンだから逆順になっているだけで指しているものは同じ・・・。
ch_ptrをuiにも変換できてる・・・。
Sample/reinterpret_cast.cpp at master · bg1bgst333/Sample · GitHub