繁体   English   中英

在C#中传递包含数组的结构指针作为参数

[英]Passing a struct pointer which contains an array as a parameter in C#

我在C ++中有一个函数,并在DLL中导出。 功能是

LONG LOGIN(LPDEVINFO info);

LPDEVINFO的结构为:

struct{  
       BYTE sSerialNumber[20];
} *LPDEVINFO;

为了传递LPDEVINFO参数,我在托管代码中定义了一个类:

class DEVINFO{
     Byte[] sSerialNumber = new Byte[20];
}

然后像这样P / Invoke:

[DllImport ('MyDll.dll')]
public static extern Int32 LOGIN(DEVINFO info);

然后在C#中调用它:

DEVINFO info = new DEVINFO();
Int id = LOGIN(info)

运行此代码时,出现以下错误:

An unhandled exception of type 'System.AccessViolationException' occurred in WindowsFormsApplication1.exe

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

我认为问题是由数组sSerialNumber引起的。 但是我不知道如何正确定义它。

提前致谢!

使用fixed关键字声明一个包含固定大小缓冲区的结构:

public unsafe struct DevInfo
{
    public fixed byte sSerialNumber[20];
}

有关更多信息,请参见固定大小缓冲区

另外,要通过指针传递结构(对应于本机端的LPDEVINFO ),请声明函数,如下所示:

[DllImport ('MyDll.dll')]
public static extern Int32 LOGIN(ref DevInfo info);

并称之为:

DevInfo info = new DevInfo();
int id = LOGIN(ref info)

我会在这里使用UmanagedType.ByValArray

class DEVINFO {
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=20)]
    public byte[] sSerialNumber;
}

否则对我来说一切都很好。 特别是,最好使用class而不是struct来执行此操作。

该函数期望指向结构而不是实际结构的指针。

使用Marshal.StructureToPtr()函数将您的结构转换为IntPtr。

C#中的示例:

[DllImport("MyDll.dll")]
public static extern Int32 LOGIN(IntPtr info);

...

DEVINFO info = new DEVINFO();
IntPtr infoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(info));
Marshal.StructureToPtr(info, infoPtr, false);
LOGIN(infoPtr);

如果这是一个OUT参数,则由于被调用者对其进行了修改,因此您需要在调用该函数后从中读取该参数,然后使用Marshal.PtrToStructure将其读回到托管结构中,如下所示:

DEVINFO info = (DEVINFO)Marshal.PtrToStructure(infoPtr, typeof(DEVINFO));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM