簡體   English   中英

在 C# 中將結構指針作為參數傳遞

[英]Passing a struct pointer as paramater in C#

我需要包含一個 .dll,其中包含以下 C/C++ 函數原型和結構定義:

typedef struct
{
    unsigned short us1;
    unsigned short us2;
    unsigned short data[16];
} myStruct;
int myFunc(myStruct *MYSTRUCT);

為了使用這個函數,我創建了一個新類:

static class DLL
{
public struct MyStruct
    {
     public ushort us1;
     public ushort us2; 
     public ushort[] data;
     public PDPORT(ushort[] temp1, ushort temp2, ushort temp3)
     {
         us1 = temp2;
         us2 = temp3;
         data = temp1;
     }
    };
    [DllImport("PDL65DLL.dll")]
    public static extern int mvb_PutPort(ref MyStruct CommData);
}

在我的主類中,我初始化 struct 變量並像這樣調用函數:

    DLL.MyStruct communicationData = new DLL.MyStruct(new ushort[16], new ushort(), new ushort());
             DLL.MyFunc( ref communicationData);

但是,這似乎不起作用。 函數正在傳遞一些東西但不是正確的值,我建議它與指針使用有關。 也許 struct* 與 ref struct 不一樣......有人可以解釋問題是什么嗎?

您可能需要指定結構的包裝(取決於 C++ 代碼使用的默認包裝)。 您還可以使用[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]為編組指定固定大小的數組。

您也不需要 C# 實現來使用struct ,對於相當大的數據,我建議使用類。

下面是一個例子:

[StructLayout(LayoutKind.Sequential, Pack=4)]
public sealed class MyStruct
{
    public ushort   us1;
    public ushort   us2;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public ushort[] data;

    public MyStruct(ushort[] temp1, ushort temp2, ushort temp3)
    {
        us1  = temp2;
        us2  = temp3;
        data = new ushort[16];
        Array.Copy(temp1, data, Math.Min(temp1.Length, data.Length));
    }
}

請注意構造函數如何確保數組的大小正確。 您必須始終確保數組的大小與SizeConst聲明相匹配。

通過這些更改,Marshaller 應該會為您處理一切事務。

C/C++ 結構更像是一個“固定緩沖區”:

    unsafe struct MyStruct
    {
        ushort us1, us2;
        fixed ushort data[16];
    }

這與數組不同,在 C# 代碼中使用起來有點尷尬,但是:這是可能的。

我不是 100% 確定,但我相信您還應該在 P/Invoke 層中使用非托管指針:

public static extern int mvb_PutPort(MyStruct* CommData);

這意味着您需要通過以下方式調用它:

fixed (MyStruct* ptr = whateverYouWereGoingToPass)
{
    mvb_PutPort(ptr);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM