Handles and pointers...
-
Is this;
void bar( data_struct_t * structure ) { stuff_handle_ = GCHandle::Alloc( structure ); data_struct_t * tmp = static_cast<data_struct_t*>(stuff_handle_.Target); tmp->data_ = 1; }
effectively as safe as, or the same as, this ?void bar( data_struct_t * structure ) { data_struct_t __pin * pinned = structure; pinned->data_ = 1; }
-=jarl=- -
Is this;
void bar( data_struct_t * structure ) { stuff_handle_ = GCHandle::Alloc( structure ); data_struct_t * tmp = static_cast<data_struct_t*>(stuff_handle_.Target); tmp->data_ = 1; }
effectively as safe as, or the same as, this ?void bar( data_struct_t * structure ) { data_struct_t __pin * pinned = structure; pinned->data_ = 1; }
-=jarl=-Not really. GCHandle is more versatile than a pointer pinned via __pin. A pinned pointer only remains pinned while it is in scope, and if not set to zero. For example, when a function that uses pinned pointers returns, any pinned objects are no longer pinned. I suppose one could just say the __pin is used on stack-allocated pointers. GCHandle, on the other hand, allocates on the heap (which is why Free() must be called to release an Alloc()-allocated GCHandle). There are a few options for GCHandles, but a regular one stays allocated between function calls, like any object allocated via malloc() or unmanaged new. Which is safer? Well, that depends on the lifetime requirements you have for the object in question. If the handle needs to remain pinned/valid when it goes out of scope, GCHandle would be the safe bet. Cheers
-
Not really. GCHandle is more versatile than a pointer pinned via __pin. A pinned pointer only remains pinned while it is in scope, and if not set to zero. For example, when a function that uses pinned pointers returns, any pinned objects are no longer pinned. I suppose one could just say the __pin is used on stack-allocated pointers. GCHandle, on the other hand, allocates on the heap (which is why Free() must be called to release an Alloc()-allocated GCHandle). There are a few options for GCHandles, but a regular one stays allocated between function calls, like any object allocated via malloc() or unmanaged new. Which is safer? Well, that depends on the lifetime requirements you have for the object in question. If the handle needs to remain pinned/valid when it goes out of scope, GCHandle would be the safe bet. Cheers