我正在尝试将原始结构从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?

最佳答案

您在这里有两个错误:

语义上,您正在设置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()的顺序。

10-07 13:12
查看更多