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

标签 c# struct interop pinvoke optional-parameters

<分区>

所以我遇到了这种不幸的情况,正如标题所说,我必须编写一个带有可选 struct 参数的函数声明。

这是结构:

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
  public int nLength;
  public IntPtr lpSecurityDescriptor;
  public int bInheritHandle;
}

这是 .dll 中的函数 advapi.dll :

LONG WINAPI RegSaveKey(
_In_     HKEY                  hKey,
_In_     LPCTSTR               lpFile,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes
);

到目前为止,这是我的声明:

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

最佳答案

为此,您应该将第三个参数声明为 IntPtr。 当你想传递 null 时,给它 IntPtr.Zero。 如果你想向它传递一个真实的结构,Marshal 结构到内存中 - 即像这样的东西

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

关于c# - 如何在 C# 中传递作为结构的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47578423/

相关文章:

c# - 编码 C# 枚举数组以在 C++ 代码中修改

c# - AvalonDock MVVM 锚定位置

c# - 单击文本框后删除文本

c# - Autofac : ComponentNotRegisteredException after web site restart

c - 使用Struct和指针的程序中的不确定性(C语言程序)

c - 为什么当我试图找到结构指针的差异时会出现垃圾值?

c - 在结构内动态分配结构

c# - 在 C# 中使用互操作以独占模式打开 excel 文件

c# - using block什么时候调用dispose方法

java - 通过 Web 服务将 .NET 应用程序与 Java/J2EE 应用程序集成