C# 如何在C中传递作为结构的可选参数#

C# 如何在C中传递作为结构的可选参数#,c#,struct,interop,pinvoke,optional-parameters,C#,Struct,Interop,Pinvoke,Optional Parameters,因此,我遇到了这种不幸的情况,正如标题所说,我必须用可选的struct参数编写函数声明 这是结构的struct: [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public int bInheritHandle; } 以下是.dll中的函数: 以下是我迄今为止的声明: [

因此,我遇到了这种不幸的情况,正如标题所说,我必须用可选的
struct
参数编写函数声明

这是结构的
struct

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
  public int nLength;
  public IntPtr lpSecurityDescriptor;
  public int bInheritHandle;
}
以下是.dll中的函数:

以下是我迄今为止的声明:

[DllImport("advapi32.dll", SetLastError = true)]
static extern int RegSaveKey(UInt32 hKey, string lpFile, [optional parameter here!!] );

为此,应将第三个参数声明为
IntPtr
。 如果要将其传递为null,请将其设置为
IntPtr.Zero
。 如果你想传递一个真实的结构给它,
封送
这个结构到内存中,比如这样

SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
// set anything you want in the sa structure here

IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)));
try {
    Marshal.StructureToPtr(sa, pnt, false)

    // call RegSaveKey here 
} finally {
    Marshal.FreeHGlobal(pnt);
}

这有用吗?我认为您需要用[Out,Optional]声明最后一个参数,如下所示,声明一个类而不是一个结构。不要在pinvoke声明中使用
ref
。现在您可以传递
null
。或者,如果很少使用此参数,只需将该参数声明为IntPtr并传递IntPtr.Zero即可。
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
// set anything you want in the sa structure here

IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)));
try {
    Marshal.StructureToPtr(sa, pnt, false)

    // call RegSaveKey here 
} finally {
    Marshal.FreeHGlobal(pnt);
}