Open lowleveldesign opened 1 year ago
Tagging subscribers to this area: @dotnet/interop-contrib See info in area-owners.md if you want to be subscribed.
Author: | lowleveldesign |
---|---|
Assignees: | - |
Labels: | `api-suggestion`, `area-System.Runtime.InteropServices`, `untriaged` |
Milestone: | - |
This is handled in Win32 via VariantClear()
. When marshaling through the IL Stubs this is handled by the VM itself. It does seem like a missing low-level API. I'm not sure it is worth adding given how long it has been missing, but we can see how the community responds.
Background and motivation
It is currently quite hard to reclaim memory allocated internally by the
Marshal.GetNativeVariantForObject
method. Let's take the following code as an example:We are leaking memory because
GetNativeVariantForObject
assigns the string to theAsBstr
property of the internalVariant
type. TheAsBstr
property internally allocates memory usingMarshal.StringToBSTR
. One solution could be to provide theMarshal.FreeNativeVariant
method, which would reclaim the internal memory.API Proposal
API Usage
Alternative Designs
Another approach that comes to my mind is to modify the
BStrWrapper
class so it will be responsible for allocating and freeing memory for the wrapped BSTR string. Then we would need to instruct the users to use the wrapper when callingGetNativeVariantForObject
as using raw string leads to a leak.GetNativeVariantForObject
already acceptsBStrWrapper
, so we won't need to modify the public API.Risks
No response