未受管理的结构

时间:2017-01-19 19:49:32

标签: c# marshalling

我在C#中收到来自C++库回调的结构指针

C++结构(包装为1):

typedef 
{
    int data1[8];
    int data2[8];
    int data3;
    int data3;  
} SomeStruct;
C#中的

我有这个等价物:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1), Serializable]
public struct SomeStruct
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
    public int[] data1

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
    public int [] data2;

    public int data3;
    public int data4;
};

var data包含正确的IntPtr

SomeStruct ss = (SomeStruct )Marshal.PtrToStructure(pointer, typeof(SomeStruct));

但是我得到了垃圾,我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

这是使用VC ++

的最简单的可行示例

您可能需要查看以下内容:

  • 代码中的一切正确吗?
  • 你使用的不是VC ++吗?
    • 如果是,则检查该编译器的打包和对齐行为

导出符号的Win32 DLL项目:

struct test
{
    int data1[8];
    int data2[8];
    int data3;
    int data4;
};

EXTERN_C MYDLL_API test* Test()
{
    test* pTest = new test;
    for (int i = 0; i < 8; i++)
    {
        pTest->data1[i] = i;
        pTest->data2[i] = i;
    }
    pTest->data3 = 1234;
    pTest->data4 = 5678;
    return pTest;
}

C#测试计划:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var intPtr = Test();
            var ptrToStructure = Marshal.PtrToStructure<Test1>(intPtr);
        }

        [DllImport("MyDLL.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr Test();
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct Test1
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public readonly int[] data1;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public readonly int[] data2;

        public readonly int data3;
        public readonly int data4;
    }
}

<强>结果:

enter image description here