How to detect if an object has been pinned #65927
-
I have a method that returns either managed or unmanaged memory
The method lives in various providers where one can return managed memory and another can return unmanaged memory. The problem is that is that I don't know if the value is pinned and I can get a pointer to the underlying data. As said above the data can be managed but could already have been pinned by On the other side there is unmanaged array where I don't need to do anything. Since the So just holding the fix inside the method is not enough. I need to fixed it over the whole lifetime of the execution. But since fixing the memory is in the hand of the implementor that calls my library I need to prevent errors by checking if the memory is indeed fixed. Any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You don't. If you need it to be pinned, you need to pin it. The alternative is you document that it must be pinned and leave it up to the caller to ensure it, being very clear about how dangerous the API is, or force the user to pin if necessary by accepting a pointer instead of a managed reference. You could also accept a |
Beta Was this translation helpful? Give feedback.
You don't. If you need it to be pinned, you need to pin it. The alternative is you document that it must be pinned and leave it up to the caller to ensure it, being very clear about how dangerous the API is, or force the user to pin if necessary by accepting a pointer instead of a managed reference. You could also accept a
Memory<T>
, which supports carrying a bit in it that let's the user say that it was created with a pinned object, and then when you call Memory.Pin, it won't create another GCHandle. Such instances can be created with MemoryMarshal.CreateFromPinnedArray.