-
Notifications
You must be signed in to change notification settings - Fork 5k
[API Proposal]: Provide API for freeing Variant memory #79402
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Tagging subscribers to this area: @dotnet/interop-contrib Issue DetailsBackground and motivationIt is currently quite hard to reclaim memory allocated internally by the var variantPtr = Marshal.AllocHGlobal(VariantTypeSize); // VariantTypeSize = 24 (x64) or 16 (x86)
Marshal.GetNativeVariantForObject("test string", variantPtr);
// pass the variantPtr to native code and do the work
Marshal.FreeHGlobal(variantPtr); We are leaking memory because API Proposalnamespace System.Runtime.InteropServices;
public static class Marshal
{
public static void FreeNativeVariant(nint addr);
} API Usagevar variantPtr = Marshal.AllocHGlobal(VariantTypeSize); // VariantTypeSize = 24 (x64) or 16 (x86)
Marshal.GetNativeVariantForObject("test string", variantPtr);
// pass the variantPtr to native code and do the work
Marshal.FreeNativeVariant(variantPtr);
Marshal.FreeHGlobal(variantPtr); Alternative DesignsAnother approach that comes to my mind is to modify the RisksNo response
|
This is handled in Win32 via |
using var variant = ComVariant.Create("test string"); // The variant struct is allocated on stack, no need for manual AllocHGlobal/FreeHGlobal
{
DoPInvoke(&variant); // Take the address of variant struct directly
}
// The using scope disposes referenced memory To work with a pointer from old flow, you can cast a pointer from it: ((ComVariant*)variantPtr)->Dispose(); |
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
The text was updated successfully, but these errors were encountered: