0

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.

  • You can get a pointer to unmanaged data. [This](https://stackoverflow.com/questions/8268625/get-pointer-on-byte-array-from-unmanaged-c-dll-in-c-sharp) answer may help. – Hamid Reza Mohammadi Apr 11 '20 at 15:36

1 Answers1

0

I can not post a comment, so I write here. This seems same to your question, it may help you.

Rick12321
  • 21
  • 4
  • In the linked example a C# array with known size gets passed to the C++ method. I want to pass an array by reference, the C++ methods stores data in the array which gets passed back to C#. I guess the problem is, that the size of the array needs to be known beforehand to allocate memory, and that info needs to be passed along. – Daniel Sonntag Apr 16 '20 at 15:14