1

我在(.dll)文件中使用 ac 函数,该文件引用结构数组并返回一个字节,该字节确定我的操作是否成功。它在 c 项目中运行良好,当我发送一个小型数组(最多 7 个元素)时运行良好,然后返回 false !

该数组来自以下结构

    [StructLayout(LayoutKind.Sequential)]
    public struct MainStruct
    {
        [MarshalAsAttribute(UnmanagedType.Struct, SizeConst = 5)]
        public Struct2 Struct2Object;

        [MarshalAsAttribute(UnmanagedType.U8, SizeConst = 1)]
        public UInt64 Elem1;

        [MarshalAsAttribute(UnmanagedType.U8, SizeConst = 1)]
        public UInt64 Elem2;

        [MarshalAsAttribute(UnmanagedType.U8, SizeConst = 1)]
        public UInt64 Elem3;

        [MarshalAsAttribute(UnmanagedType.U8, SizeConst = 1)]
        public UInt64 Elem4;

        [MarshalAsAttribute(UnmanagedType.U8, SizeConst = 1)]
        public UInt64 Elem5;

        [MarshalAsAttribute(UnmanagedType.U8, SizeConst = 1)]
        public UInt64 Elem6;

        [MarshalAsAttribute(UnmanagedType.U8, SizeConst = 1)]
        public UInt64 Elem7;

        [MarshalAsAttribute(UnmanagedType.U8, SizeConst = 1)]
        public UInt64 Elem8;

    };
4

3 回答 3

0

我已经尝试使用指针来获取数据:( .. 直到此时它工作正常。

MainStruct OBJ = (MainStruct)Marshal.PtrToStructure(pointertostruct, typeof(MainStruct));

指针获取数据,但它只是用零初始化对象!

于 2012-05-03T11:19:15.330 回答
0
    __declspec(dllexport) TU08 GetBuffer(MainStruct *OBJ)
    {
    TU64 SelectedOBIS;
    TU08 XdrBuffer[Dlms_mXdrMaxBuffer];
    TU08 *pXdrBuffer;
    TU32 i;
    TU32 NumberOfElements;

    pXdrBuffer = XdrBuffer;
    SelectedOBIS = ProfilesData[LOG_ID_1].ProfilesOBISCodes;

        pXdrBuffer = XdrBuffer;
        Dlms_gXdrInitBuffer();
        /////// Get Data ///////
        if(Main_iSendGetRequest(SelectedOBIS, 7, 2, XdrBuffer) == false)
            return 0;
        /////// Extract Data ///////
        if(*XdrBuffer == Dlms_mXdrArray)
        {
            NumberOfElements = *(pXdrBuffer + 1);
            pXdrBuffer += 2; // 2 for array tag and its number of fields 
            for(i=0; i<NumberOfElements; i++)
            {
                if(*pXdrBuffer == Dlms_mXdrStruct)
                {
    pXdrBuffer += 2; // 2 for struct tag and its number of fields 
    pXdrBuffer = gGetDateTime(pXdrBuffer, &OBJ[i].TimeStamp);
    pXdrBuffer = gGetLongUnsigned(pXdrBuffer, &OBJ[i].StatusRegister);
    pXdrBuffer = gGetUnsigned(pXdrBuffer, &OBJ[i].EventCode);
    }
            }
        }
    return 1;
}

那是使用的功能。

这是C中的结构

typedef struct
{
    Struct2 Struct2OBject;
    TU64 Elem1;
    TU64 Elem2;
    TU64 Elem3;
    TU64 Elem4;
    TU64 Elem5;
    TU64 Elem6;
    TU64 Elem7;
    TU64 Elem8;
} MainStruct;

函数的元帅是

    [DllImport("dll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern byte GetBuffer([In, Out] MainStruct[] Profile);

关键是,如果传递给函数的数组大小为 7 或更小,它在 C 中运行良好,并且在 Windows 窗体应用程序中运行良好!

于 2012-05-02T12:06:06.980 回答
0

您的结构中似乎硬编码了 8 个字节。当然,如果超过该限制,您将获得内存损坏。

如果要“发送”的字节数可能无限,我会使用 Marshal.AllocHGlobal 分配一个非托管缓冲区并将其传递给非托管函数。

于 2012-04-29T10:46:31.547 回答