0

I have been struggling 2nd day with the task how to pass a structure, containing array of byte to c++ dll. Namely, I don't know how to marshal C# structure. Here is my code:

in C++ dll:

    struct Image
    {
        int Width;
        int Height;
        int Depth;
        uchar *Data;
    };
    .....
__declspec(dllexport) void DirectTransform(Image *InImage, Image*DestImage)  
{
...Implementation...
}

in C# program:

    [StructLayout(LayoutKind.Sequential)]
     struct ImageData
    {
        public int Width;
        public int Height;
        public int Depth;
        [MarshalAs(UnmanagedType.LPArray)]
        public byte[] Data;
    }
 [DllImport("MyDll.dll",CallingConvention=CallingConvention.Cdecl)]
        public static extern void DirectTransform(ImageData Src, ImageData Dest);

//Fill out both structures..

        DirectTransform(Image, DestImage);

Exception throws at calling of DirectTransform and says that:

Cannot marshal field 'Data' of type'ImageData': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).

When I change LPArray to ByValArray and point the size of array(in this case 202500) it also doesn't work, because the size is too large. When SafeArray is used, the program fails inside DLL with the message :

Attempted to read or write protected memory. This is often an indication that other memory is corrupt. And data in structures are erroneous.

Could anyone help me?

1
  • It has to be IntPtr, initialize it with Marshal.AllocHGlobal(). The Dest argument is however a problem, you either don't know how large an array to allocate or the C code allocates it and then you have a memory leak. Commented Oct 3, 2014 at 8:37

1 Answer 1

0

Look at this question

You can try passing a pointer to your array and, for example an integer length field. Doing that, you'll need to manually allocate unmanaged memory using Marshal.AllocHGlobal, call your function and after that in finally block - clear after yourself with Marshal.FreeHGlobal

With Marshal.Copy method you are copying your data into allocated memory.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.