66#![ feature( box_as_ptr) ]
77
88use std:: mem:: MaybeUninit ;
9- use std:: ptr:: null ;
9+ use std:: ptr;
1010
1111fn main ( ) {
1212 test_increment_int ( ) ;
@@ -20,6 +20,8 @@ fn main() {
2020 test_pass_dangling ( ) ;
2121 test_swap_ptr_triple_dangling ( ) ;
2222 test_return_ptr ( ) ;
23+ test_pass_ptr_as_int ( ) ;
24+ test_pass_ptr_via_previously_shared_mem ( ) ;
2325}
2426
2527/// Test function that modifies an int.
@@ -112,7 +114,7 @@ fn test_swap_ptr() {
112114 }
113115
114116 let x = 61 ;
115- let ( mut ptr0, mut ptr1) = ( & raw const x, null ( ) ) ;
117+ let ( mut ptr0, mut ptr1) = ( & raw const x, ptr :: null ( ) ) ;
116118
117119 unsafe { swap_ptr ( & mut ptr0, & mut ptr1) } ;
118120 assert_eq ! ( unsafe { * ptr1 } , x) ;
@@ -131,7 +133,7 @@ fn test_swap_ptr_tuple() {
131133 }
132134
133135 let x = 71 ;
134- let mut tuple = Tuple { ptr0 : & raw const x, ptr1 : null ( ) } ;
136+ let mut tuple = Tuple { ptr0 : & raw const x, ptr1 : ptr :: null ( ) } ;
135137
136138 unsafe { swap_ptr_tuple ( & mut tuple) }
137139 assert_eq ! ( unsafe { * tuple. ptr1 } , x) ;
@@ -148,7 +150,7 @@ fn test_overwrite_dangling() {
148150 drop ( b) ;
149151
150152 unsafe { overwrite_ptr ( & mut ptr) } ;
151- assert_eq ! ( ptr, null( ) ) ;
153+ assert_eq ! ( ptr, ptr :: null( ) ) ;
152154}
153155
154156/// Test function that passes a dangling pointer.
@@ -200,3 +202,33 @@ fn test_return_ptr() {
200202 let ptr = unsafe { return_ptr ( ptr) } ;
201203 assert_eq ! ( unsafe { * ptr } , x) ;
202204}
205+
206+ /// Test casting a pointer to an integer and passing that to C.
207+ fn test_pass_ptr_as_int ( ) {
208+ extern "C" {
209+ fn pass_ptr_as_int ( ptr : usize , set_to_val : i32 ) ;
210+ }
211+
212+ let mut m: MaybeUninit < i32 > = MaybeUninit :: uninit ( ) ;
213+ unsafe { pass_ptr_as_int ( m. as_mut_ptr ( ) as usize , 42 ) } ;
214+ assert_eq ! ( unsafe { m. assume_init( ) } , 42 ) ;
215+ }
216+
217+ fn test_pass_ptr_via_previously_shared_mem ( ) {
218+ extern "C" {
219+ fn set_shared_mem ( ptr : * mut * mut i32 ) ;
220+ fn init_ptr_stored_in_shared_mem ( val : i32 ) ;
221+ }
222+
223+ let mut m: * mut i32 = ptr:: null_mut ( ) ;
224+ let ptr_to_m = & raw mut m;
225+ unsafe { set_shared_mem ( & raw mut m) } ;
226+
227+ let mut m2: MaybeUninit < i32 > = MaybeUninit :: uninit ( ) ;
228+ // Store a pointer to m2 somewhere that C code can access it.
229+ unsafe { ptr_to_m. write ( m2. as_mut_ptr ( ) ) } ;
230+ // Have C code write there.
231+ unsafe { init_ptr_stored_in_shared_mem ( 42 ) } ;
232+ // Ensure this memory is now considered initialized.
233+ assert_eq ! ( unsafe { m2. assume_init( ) } , 42 ) ;
234+ }
0 commit comments