I have the following types in C++:
typedef void* keychain_handle;
typedef struct {
const char* keyHolderName;
unsigned int numKeys;
key* keys;
} key_holder;
typedef struct {
const char* keyName;
unsigned int keySize;
} key;
And I have the following methos:
int createKeyChain(
int id,
key_holder* keyHolders,
keychain_handle* handle);
I need my C# to create key holders with keys, send it to the C++ code and receive a handle.
This is my C# code:
/* Structs */
[StructLayout(LayoutKind.Sequential)]
public struct Key
{
public string key;
public uint size;
}
[StructLayout(LayoutKind.Sequential)]
public struct KeyHolder
{
public string name;
public uint keys;
public IntPtr keys;
}
/* Sync API */
[DllImport("keys.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern uint createKeyChain(uint id, KeyHolder[] keyHolders, ref IntPtr handle);
Key[] myKeys = new Key[1];
myKeys[0] = new Key { key = "tst", size = 5 };
KeyHolder keyHolder = new DllWrapper.KeyHolder
{
name = "tst123",
items = 1,
keys = Marshal.AllocHGlobal(Marshal.SizeOf(typeof (Key))*myKeys.Length)
};
IntPtr c = new IntPtr(keyHolder.keys.ToInt32());
for (int i = 0; i < myKeys.Length; i++)
{
Marshal.StructureToPtr(myKeys[i], c, false);
c = new IntPtr(c.ToInt32() + Marshal.SizeOf(typeof(Key)));
}
Marshal.StructureToPtr(c, keyHolder.keys, false);
IntPtr handle = IntPtr.Zero;
var ret = createKeyChain(111, new []{keyHolder}, ref handle);
Everything is working well except for the internal string inside the Key object, which is corrupt. I suspect it is the StructureToPtr that is corrupting it. How can I make the string show on the C++ side?
Thanks.