Search code examples
c#arraysdynamicpinvokemarshalling

Invalid Managed/Unmanaged Type Combination With Embedded, Dynamically-Allocated Array


I have a common construct in an unmanaged Win32 C++ DLL:

// FirstElemPtrContainer.h
#include "stdafx.h"

typedef unsigned char elem_type; // a byte

typedef struct FirstElemPtrContainer {
    unsigned char num_elems;
    void *allocd_ary;
} FirstElemPtrContainer;

The void* in the struct is meant to contain a pointer to the first element of an allocated byte array.

The DLL that uses this definition then exports functions to allocate, populate, and deallocate the struct:

// The exported allocator function.
extern "C" _declspec(dllexport) 
    FirstElemPtrContainer *BuildStruct(int elem_count)
{
    FirstElemPtrContainer *fepc_ptr = new FirstElemPtrContainer;
    fepc_ptr->num_elems = elem_count;
    elem_type *ary = new elem_type[fepc_ptr->num_elems];
    for (int i = 0; i < fepc_ptr->num_elems; i++)
    {
        ary[i] = ((i + 1) * 5); // multiples of 5
    }
    fepc_ptr->allocd_ary = ary;

    return fepc_ptr;
}

// The exported deallocator function.
extern "C" _declspec(dllexport) void 
    DestroyStruct(FirstElemPtrContainer *fepc_ptr)
{
    delete[] fepc_ptr->allocd_ary;
    delete fepc_ptr;
}

These work just fine for a native caller.

In C#, I try to describe this same structure via PInvoke:

[StructLayout(LayoutKind.Sequential)]
public struct FirstElemPtrContainer
{
    public byte num_elems;
    [MarshalAs(UnmanagedType.LPArray, 
        ArraySubType = UnmanagedType.U1, SizeConst = 4)]
    public IntPtr allocd_ary;
}

... and describe the call interface like so:

public static class Imports
{
    [DllImport("MyLib", CallingConvention = CallingConvention.Winapi)]
    public static extern IntPtr BuildStruct(int elem_count);

    [DllImport("MyLib", CallingConvention = CallingConvention.Winapi)]
    public static extern void DestroyStruct(IntPtr fepc_ptr);
}

Now I attempt to call my interface:

class Program
{
    const int NUM_ELEMS = 4;
    static void Main(string[] args)
    {
        IntPtr fepc_ptr = Imports.BuildStruct(NUM_ELEMS);
        if ( fepc_ptr == IntPtr.Zero ) 
        {
            Console.WriteLine("Error getting struct from PInvoke.");
            return;
        }

        FirstElemPtrContainer fepc =
            (FirstElemPtrContainer)Marshal.PtrToStructure(fepc_ptr, 
        typeof(FirstElemPtrContainer));
        //...
    }
}

The PtrToStructure() call gives the error "Cannot marshal field 'allocd_ary' of type 'MyLibInvoke.FirstElemPtrContainer': Invalid managed/unmanaged type combination (Int/UInt must be paired with SysInt or SysUInt)."

You can see that I've hard-coded a particular number of elements, which we'll assume the caller adheres to. I've also added an ArraySubType clause, though it seems not to make a difference. Why the type mismatch complaint?


Solution

  • Your struct should be declared like this:

    [StructLayout(LayoutKind.Sequential)]
    public struct FirstElemPtrContainer
    {
        public byte num_elems;
        public IntPtr allocd_ary;
    }
    

    it has to be done this way because allocd_ary is a pointer to unmanaged memory and cannot be marshalled by the p/invoke marshaller.

    In order to read the contents of allocd_ary you can use Marshal.Copy.

    FirstElemPtrContainer fepc = (FirstElemPtrContainer)Marshal.
        PtrToStructure(fepc_ptr, typeof(FirstElemPtrContainer));
    byte[] ary = new byte[fepc.num_elems];
    Marshal.Copy(fepc.allocd_ary, ary, 0, ary.Length);
    

    I suspect that CallingConvention.Winapi is wrong and that you should be using CallingConvention.Cdecl.