Work with PCZZWSTR
#1299
-
I'm currently struggling on how to interact with PCZZWSTR. PCZZWSTR has a constructor that takes a char*. How can I convert one or more strings to this structure? |
Beta Was this translation helpful? Give feedback.
Answered by
AArnott
Oct 31, 2024
Replies: 1 comment 1 reply
-
The simplest way to demonstrate is this: unsafe
{
string message = "message1\0message2\0\0";
fixed (char* pMessage = message)
{
PCZZWSTR wstr = new(pMessage);
}
} Note that this doesn't copy the memory, it merely points to it. So the If you want to use it longer term, you can allocate native memory: using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Windows.Win32.Foundation;
string[] strings = ["message1", "message2"];
PCZZWSTR list = CreateStringList(strings);
try
{
// use it here.
}
finally
{
FreeStringList(ref list);
}
// Allocates native memory and copies an array of strings into it.
static unsafe PCZZWSTR CreateStringList(string[] values)
{
// The length of the buffer is the sum of the individual string lengths, plus their null terminators, plus one more null terminator.
int charLength = values.Sum(v => v.Length + 1) + 1;
int byteLength = charLength * sizeof(char);
char* p = (char*)Marshal.AllocHGlobal(byteLength);
Span<char> remainingSpan = new(p, charLength);
foreach (string value in values)
{
value.AsSpan().CopyTo(remainingSpan);
remainingSpan[value.Length] = '\0';
remainingSpan = remainingSpan.Slice(value.Length + 1);
}
remainingSpan[0] = '\0';
Debug.Assert(remainingSpan.Length == 1);
return new PCZZWSTR(p);
}
static unsafe void FreeStringList(ref PCZZWSTR list)
{
Marshal.FreeHGlobal((IntPtr)list.Value);
list = default;
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
sensslen
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The simplest way to demonstrate is this:
Note that this doesn't copy the memory, it merely points to it. So the
wstr
I initialize here is only valid while you're inside thefixed
block.If you want to use it longer term, you can allocate native memory: