How to convert C# String[] to PCWSTR* for using by PInvoke.InitPropVariantFromStringVector #1135
Answered
by
AArnott
harborsiem
asked this question in
Q&A
-
What is the best way to convert a String array to a PCWSTR* for using by PInvoke.InitPropVariantFromStringVector(PCWSTR*, uint, out PROPVARIANT) function? I have done it this way with GCHandle pinning for every String. /// <summary>
/// Converts a string array to a PROPVARIANT
/// with pinned strings, so the GC can't move the strings in memory till PInvoke function is called
/// </summary>
/// <param name="strings"></param>
/// <param name="propVar"></param>
/// <returns></returns>
internal static unsafe HRESULT InitPropVariantFromStringVector(string[] strings, out PROPVARIANT propVar)
{
HRESULT hr;
PCWSTR[] array = new PCWSTR[strings.Length];
GCHandle[] pins = new GCHandle[strings.Length];
for (int i = 0; i < array.Length; i++)
{
if (strings[i] != null)
pins[i] = GCHandle.Alloc(strings[i], GCHandleType.Pinned);
else
pins[i] = GCHandle.Alloc(string.Empty, GCHandleType.Pinned);
array[i] = (char*)pins[i].AddrOfPinnedObject();
}
fixed (PCWSTR* parray = array)
hr = PInvoke.InitPropVariantFromStringVector(parray, (uint)strings.Length, out propVar);
for (int i = 0; i < pins.Length; i++)
{
if (pins[i].IsAllocated)
pins[i].Free();
}
return hr;
} |
Beta Was this translation helpful? Give feedback.
Answered by
AArnott
Feb 22, 2024
Replies: 1 comment 2 replies
-
That's a good approach, IMO. I would add |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
harborsiem
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's a good approach, IMO. I would add
try
/finally
blocks to ensure that an exception thrown wouldn't leak memory, but otherwise it's decent.