将C ++非托管代码转换为C#

时间:2017-06-20 14:44:36

标签: c# c++ marshalling

我正在尝试使用Marshal在C#中使用C ++ DLL代码。 它有两个结构作为指针参数传递到导出的API中,但它在C#中给出的结构响应值不是正确的顺序。虽然它在VC ++中运行良好。

ELSE

我在C#中实现了什么:

//C++ Code - Working
//Structure 1
typedef struct
{
    bool    bExist;
    bool    bAvailable;
    int     iNoteNumber;
    int     iDispenseNumber;
    int     iOutNoteNumber;
    char    cStatus;
    char    acBoxID[6];
} tHopperStatus;
//Structure 2
typedef struct 
{
    char acCurrency[4]; 
    int lDenomination;  
    int iRemainCount;   
    int iCount; 
    int iOutCount;
    int iRejectCount;
    int iPurgeCount;    
    BYTE    byHopper;
    char    cStatus;
    char    cLastStatus;    
    char    acBoxID[6];
    BYTE    byBoxType;
    char    acReserved1[10];
    char    acReserved2[10];
    int iReserverd1;
    int iReserverd2;
} tCashBox;
//API using above two structures
int iGetCassette(tCashBox* p_psCashBox,tDevReturn* p_psStatus);

//Calling API by passing pointer of Structure Array  
tCashBox l_asBox[8] = {0};
tDevReturn l_asReturn[8] = {0};
int l_iRes = l_pDev->iGetCassette(l_asBox, l_asReturn);

我有一个疑问,在C#中是否允许以这种方式传递Array of Structure,就像在C ++中一样。如果有人可以帮助我,那将是一个很大的帮助。提前谢谢。

编辑: 我更改了“取消”的数据类型'从long到int。现在,数组第一个元素正在填满。但结构数组的剩余七个元素没有被填满。

如果有人可以帮助我,如何创建包含所有具有内存顺序的元素的结构数组。

1 个答案:

答案 0 :(得分:0)

最终通过以下更新的结构2解决了问题: 1.更改了“取消”的数据类型'从long到int。 2.在struct layout parameters中添加了Pack = 1和CharSet = CharSet.Ansi。

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct tCashBox
{
    public tCashBox(int param)
    {
        acCurrency = new char[4];
        lDenomination = 0;
        iRemainCount = 0;
        iCount = 0;
        iOutCount = 0;
        iRejectCount = 0;
        iPurgeCount = 0;
        byHopper = 0;
        cStatus = '\0';
        cLastStatus = '\0';
        acBoxID = new char[6];
        byBoxType = 0;
        acReserved1 = new char[10];
        acReserved2 = new char[10];
        iReserverd1 = 0;
        iReserverd2 = 0;
    }
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public char[] acCurrency;
    public int lDenomination;
    public int iRemainCount;
    public int iCount;
    public int iOutCount;
    public int iRejectCount;
    public int iPurgeCount;
    public byte byHopper;
    public char cStatus;
    public char cLastStatus;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
    public char[] acBoxID;
    public byte byBoxType;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public char[] acReserved1;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public char[] acReserved2;
    public int iReserverd1;
    public int iReserverd2;
}