Skip to content

Is there a way to temporarily store managed pointers in a stackalloc buffer without incurring unexpected behavior from the GC? #106653

Answered by EgorBo
operation404 asked this question in Q&A
Discussion options

You must be logged in to vote

There is nothing wrong with just storing gc references on stack (not sure why stackalloc doesn't support managed types - there are proposals like #33960 and related links) - you can define a struct with gc fields and put it on stack.

I know the objects won't be freed as they're still referenced by the original heap allocated collections. But I want to ensure the objects won't be moved by the GC while calling a function with these stack buffers. Is this possible?

If you don't want them to be moved, you have to pin every object in your buffer, otherwise GC may change pointers in your buffer while native code is doing something with them (see e.g. GCHandle)

Replies: 2 comments 14 replies

Comment options

You must be logged in to vote
6 replies
@operation404
Comment options

@josephmoresena
Comment options

@operation404
Comment options

@josephmoresena
Comment options

@operation404
Comment options

Comment options

You must be logged in to vote
8 replies
@EgorBo
Comment options

@operation404
Comment options

@josephmoresena
Comment options

@EgorBo
Comment options

@operation404
Comment options

Answer selected by operation404
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants