编组后的现场价值错误

时间:2013-01-04 16:02:54

标签: c# c++ marshalling

我正在尝试将原始结构从C ++编组到C#,并有以下代码:

using System;
using System.Runtime.InteropServices;

namespace dotNet_part
{
    class Program
    {
        static void Main(string[] args)
        {
            Custom custom = new Custom();
            Custom childStruct = new Custom();

            IntPtr ptrToStructure = Marshal.AllocCoTaskMem(Marshal.SizeOf(childStruct));
            Marshal.StructureToPtr(childStruct, ptrToStructure, true);

            custom.referenceType = ptrToStructure;
            custom.valueType = 44;

            Custom returnedStruct = structureReturn(custom);
            Marshal.FreeCoTaskMem(ptrToStructure);

            returnedStruct = (Custom)Marshal.PtrToStructure(returnedStruct.referenceType, typeof(Custom));
            Console.WriteLine(returnedStruct.valueType); // Here 'm receiving 12 instead of 44
        }

        [return:MarshalAs(UnmanagedType.I4)]
        [DllImport("CPlusPlus part.dll")]
        public static extern int foo(Custom param);

        // [return:MarshalAs(UnmanagedType.Struct)]
        [DllImport("CPlusPlus part.dll")]
        public static extern Custom structureReturn(Custom param);
    }

    [StructLayout(LayoutKind.Sequential)]
    struct Custom
    {
        [MarshalAs(UnmanagedType.I4)]
        public int valueType;
        public IntPtr referenceType;
    }
}

和C ++部分:

typedef struct Custom CUSTOM;
extern "C"
{
    struct Custom
    {
       int valueType;
       Custom* referenceType;
    } Custom;

    _declspec(dllexport) int foo(CUSTOM param)
    {
      return param.referenceType->valueType;
    }

    _declspec(dllexport) CUSTOM structureReturn(CUSTOM param)
    {
      return param;
    }
}

为什么我在returnedStruct.valueType收到12而不是44?

1 个答案:

答案 0 :(得分:4)

这里有两个错误:

从语义上讲,您正在设置custom.valueType = 44但是在返回结构时,您正在检查custom.referenceType->valueType,它不应该是44 - 它应该是0.

第二个错误是你在解组它之前在这个指针(Marshal.FreeCoTaskMem()上调用custom.referenceType!这意味着您将未分配的内存解组到您的Custom结构中。此时,这是未定义的行为,12的答案与接收访问冲突的结果一样有效。


要解决第一个问题,您需要先检查returnedStruct.valueType 而不解组returnedStruct.referenceType,或者在编组之前需要将childStruct.valueType设置为44进入ptrToStructure

要解决第二个问题,您需要撤消调用Marshal.PtrToStructure()Marshal.FreeCoTaskMem()的顺序。