c# - 在 C# 中将结构体指针作为参数传递

标签 c# c++ pointers struct parameters

我需要包含一个 .dll,其中包含以下 C/C++ 函数原型(prototype)和结构定义:

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);
}

在我的主类中,我初始化结构变量并调用函数,如下所示:

    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# 中将结构体指针作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63593102/

相关文章:

c - 将 unsigned char 指针传递给 atoi 而不进行强制转换

c# - ExecuteNonQuery 不更新输出参数

c# - 如何使用 SQL 查询更新表中的多行?

c++ - UWidgetComponent 未在蓝图编辑器中显示详细信息

c++ - 我可以更改默认继承的访问器吗?

c# - 如何在 C++ 和 C# 之间共享一个大字节数组

C++ lambda 表达式 : captured pointer to STL container changing address after pop?

c# - 将平面线性树表示转换为内存树表示

c# - 你如何在 xaml 的 ListView 中拉伸(stretch)图像?

c++ - qpainter 绘画替代品(在 Mac 上性能很差)