嵌入式,动态分配的阵列无效的托管/非托管类型组合

时间:2012-04-09 16:20:16

标签: c# arrays dynamic pinvoke marshalling

我在非托管的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;

struct中的void *意味着包含指向已分配字节数组的第一个元素的指针。

使用此定义的DLL然后导出函数以分配,填充和取消分配结构:

// 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;
}

这些工作对于本地调用者来说很好。

在C#中,我试图通过PInvoke来描述这个相同的结构:

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

...并像这样描述调用界面:

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);
}

现在我尝试拨打我的界面:

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));
        //...
    }
}

PtrToStructure()调用给出错误“无法封送'MyLibInvoke.FirstElemPtrContainer'类型的字段'allocd_ary':无效的托管/非托管类型组合(Int / UInt必须与SysInt或SysUInt配对)。”

你可以看到我已经硬编码了特定数量的元素,我们假设调用者遵守这些元素。我还添加了一个ArraySubType子句,虽然它似乎没有什么区别。为什么类型不匹配投诉?

1 个答案:

答案 0 :(得分:2)

你的结构应该像这样声明:

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

必须以这种方式完成,因为allocd_ary是指向非托管内存的指针,不能由p / invoke marshaller编组。

要阅读allocd_ary的内容,您可以使用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);

我怀疑CallingConvention.Winapi错误,您应该使用CallingConvention.Cdecl