简体   繁体   English

从C#到VC ++的结构体编组数组

[英]Marshalling array of struct from C# to VC++

I'm trying to marshal an array of structs from C# to VC++. 我试图封送从C#到VC ++的结构数组。

The C++ function looks like this: C ++函数如下所示:

void myFunc(tFileListEntry* fileList);

And tFileListEntry is defined as: tFileListEntry定义为:

typedef struct FILE_LIST
{
    uint16_t FileGroupCounter;
    uint32_t FileID;
    uint16_t NumbSamples;
} tFileListEntry;

In C# I declared the function like this: 在C#中,我声明了如下函数:

[DllImport("MyLib", EntryPoint = "myFunc", CallingConvention = CallingConvention.Cdecl)]
public static extern void myFunc( [In, MarshalAs(UnmanagedType.LPArray)] tFileListEntry[] fileList);

And tFileListEntry is defined as: tFileListEntry定义为:

[StructLayout(LayoutKind.Sequential)]
public class tFileListEntry
{
    public tFileListEntry(UInt16 fileGroupCounter, UInt32 fileId, UInt16 numbSamples)
    {
        FileGroupCounter = fileGroupCounter;
        FileID = fileId;
        NumbSamples = numbSamples;
    }

    public UInt16 FileGroupCounter;
    public UInt32 FileID;
    public UInt16 NumbSamples;
}

I can set a breakpoint in the C# code as well as in the C++ library. 我可以在C#代码和C ++库中设置断点。 On the managed side the values look right, but on the unmanaged side I get only garbage. 在托管方面,这些值看起来正确,但是在非托管方面,我只会得到垃圾。

I verified with Marshal.SizeOf() (in C#) and sizeof() (in C++) that the size of the struct is 12 bytes on both sides, so I don't think that padding/packing is an issue here. 我用Marshal.SizeOf() (在C#中)和sizeof() (在C ++中)进行了验证,该结构的大小在两侧都是12个字节,因此我认为这里的填充/打包不是问题。

What am I doing wrong? 我究竟做错了什么?

I think the problem here is that on the C# side you have declared it as a class, not as a struct. 我认为这里的问题是,在C#端,您已将其声明为类,而不是结构。

That means when you create the array on the C# side, each element of the array is a reference (4 or 8 bytes depending on the archtecture) not a struct (12 bytes), with the results you are seeing. 这意味着,当您在C#端创建数组时,数组的每个元素都是一个引用(根据体系结构为4或8个字节),而不是一个结构(12个字节),并带有结果。

Try changing the C# class to struct. 尝试将C#类更改为struct。

It looks like the problem was that I defined tFileListEntry as class on the C# side. 看来问题出在我在C#端将tFileListEntry定义为class When I change it to struct , everything works fine. 当我将其更改为struct ,一切正常。

Interestingly, I have another C++ function in the same library which accepts a single struct (not an array) and I can successfully marshal a C# class (with MarshalAs(UnmanagedType.LPStruct) ). 有趣的是,我在同一库中有另一个C ++函数,该函数接受单个struct (而不是数组),并且我可以成功编组C# class (使用MarshalAs(UnmanagedType.LPStruct) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM