C# 如何定义新的指针结构

C# How to define new pointer struct?

本文关键字:指针 结构 定义 何定义      更新时间:2023-10-16

此结构定义于 http://msdn.microsoft.com/en-us/library/windows/hardware/ff541621%28v=vs.85%29.aspx

typedef struct _FILTER_MESSAGE_HEADER {
  ULONG     ReplyLength;
  ULONGLONG MessageId;
} FILTER_MESSAGE_HEADER, *PFILTER_MESSAGE_HEADER;

我在C# code中将其定义如下:

[StructLayout(LayoutKind.Sequential)]
public struct FILTER_MESSAGE_HEADER {
      public uint replyLength;
      public ulong messageId;
};

我只在C# code中定义FILTER_MESSAGE_HEADER,PFILTER_MESSAGE_HEADER不是。

我应该如何定义PFILTER_MESSAGE_HEADER

P/S:我想定义PFILTER_MESSAGE_HEADER在函数中使用此结构。

您不必(不能)定义PFILTER_MESSAGE_HEADER。 只需将其指定为outref即可。

[DllImport("foo")]
void SomeMethod(ref FILTER_MESSAGE_HEADER lpMessageBuffer);


如果您对FilterGetMessage特别感兴趣,我不确定从中导出任何dll,但是一种可能的签名如下:

[DllImport(fltmgr, CharSet=CharSet.Unicode, ExactSpelling=true, PreserveSig=false)]
void FilterGetMessage(
    CommunicationPortSafeHandle hPort, 
    ref FILTER_MESSAGE_HEADER lpMessageBuffer,
    uint dwMessageBufferSize,
    IntPtr lpOverlapped);

我使用 PreserveSig 在发生故障时自动将HRESULT转换为异常,CharSet规范是防御性的,导致需要ExactSpellingCommunicationPortSafeHandle将是一个基于FilterConnectCommunicationPort文档从SafeHandleMinusOneIsInvalid继承的类。

您可以将此签名用作:

FILTER_MESSAGE_HEADER header;
FilterGetMessage(hFilter, ref header, 
    Marshal.SizeOf(typeof(FILTER_MESSAGE_HEADER)), IntPtr.Zero);