I am using a function from a c++ .dll from within C#. The .dll is partially documented, it was created to read out results from a result database. The function has the following signature:
cdb_get(int index, int kwh, int kwl, void *s, int *ls, int nrew);
In many cases I know the structure of the data I am reading, so I can just create a struct with the right format and read into it using regular pInvoke.
However in some cases, I need to know the first bytes of the data to figure out the correct data type. Ideally I would thus like to read the data into a byte array and then convert this further to the struct I need. I'd like to do something like this:
[DllImport("name_of_dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int cdb_get(
int index,
int kwh,
int kwl,
ref byte[] data,
ref int dataLen,
int pos);
But that doesn't seem to work (should it in theory?). Is there a way to make this work with a byte array and passing it by reference?
So far I am working arount it by using an IntPtr and then marshalling by hand. I need to guess the pointer size though, I guess that's unavoidable? Is there a different way to handle the marshalling?
IntPtr data = Marshal.AllocHGlobal(128);
int size = 128;
int returnValue = cdbGet(index, kwh, kwl, data, ref size, 1);
byteArray = new byte[size];
Marshal.Copy(data, byteArray, 0, size);
Marshal.FreeHGlobal(data);
Any help is appreciated, thanks a lot.