I'm trying to hand a string[] as byte** from C# to C++. I have to say, as a disclaimer, that I never really worked with C++ or pointers before. So I may get some things wrong. I encode and pin every string with a code like this:
var strings = new string[] { "Some string", "Another string" };
var handles = new GCHandle[string.Length];
var pointers = new byte*[string.Length];
for (int index = 0; index < strings.Length; index++)
{
var bytes = Encoding.UTF8.GetBytes(strings[index]);
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
handles[index] = handle;
pointers[index] = (byte*)handle.AddrOfPinnedObject().ToPointer();
}
//Release the handles later...
The problem I'm currently having is, that I can't pin the array that contains all the pointers. I tried to use
GCHandle.Alloc(pointers, GCHandleType.Pinned);
which throws an exception and
fixed (byte** pointer = &pointers[0])
won't work, because the array is unfixed outside the fixed block. So I thought I could maybe do something like this
byte** pointer = (byte**)this.pointers[0]
to obtain a pointer, which results in an exception, because I'm trying to read/write protected memory.
I'm currently unsure if it's even possible to accomplish, or if my approach is just wrong. Does anybody has a idea or was in a similar situation?
Thanks for the help!