在C#中包装一个C dll:结构作为函数的返回值和参数

时间:2019-03-02 17:50:00

标签: c# c dll marshalling dllimport

我需要在C#中包装一个用C编写的dll(我无法访问源代码),并且在用户定义的结构(返回和需要包装的函数的参数)方面遇到问题。

C结构:

typedef struct {
    char text[48 + 1];
    int attribute;
} ReceiptRow;

typedef struct {
    int numReceiptRows;
    int signatureRequired;
    ReceiptRow rows[200];
} Receipt;

typedef struct {
    int operationType;
    char posId[32 + 1];
    char transactionId[10 + 1];
    int isReceiptPresent;
    Receipt receipt;
} MyStruct;

C函数:

// MyFunc1 returns a pointer to the struct 
__declspec(dllexport) MyStruct* MyFunc1();

// MyFunc2 returns int and has an output MyStruct parameter
__declspec(dllexport) int MyFunc2(MyStruct* outVar);

// MyFunc3 has an input/output Mystruct parameter
__declspec(dllexport) void MyFunc3(MyStruct* inoutVar);

我已经尝试了许多使用IntPtr,ref和out的函数的解决方案,但是没有一个起作用。我希望有人能帮助我找到正确的方法,使其最终起作用。这是我用C#编写结构的方法,请指出我做错了什么。

C#

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct ReceiptRow
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 49)]
    public string text;

    public int attribute;
}

[StructLayout(LayoutKind.Sequential)]
public struct Receipt
{
    public int numReceiptRows;
    public int signatureRequired;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 200, ArraySubType = UnmanagedType.Struct)]
    public ReceiptRow[] rows;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MyStruct
{
    public int operationType;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 33)]
    public string posId;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
    public string transactionId;

    public int isReceiptPresent;

    [MarshalAs(UnmanagedType.Struct)]
    public Receipt receipt;
}

谢谢!

0 个答案:

没有答案