c# - P/invoke 函数采用指向结构的指针

标签 c# winapi interop pinvoke

<分区>

函数如CreateProcess具有指向结构的指针的签名。在 C 中,我只是将 NULL 作为可选参数的指针传递,而不是在堆栈上创建一个虚拟结构对象并将指针传递给该虚拟对象。

在 C# 中,我将其声明为 (p/invoke)

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CreateProcess(
            string lpApplicationName,
            string lpCommandLine,
            ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            bool bInheritHandles,
            CreateProcessFlags dwProcessCreationFlags,
            IntPtr lpEnvironment,
            string lpCurrentDirectory,
            ref STARTUPINFO lpStartupInfo,
            ref PROCESS_INFORMATION lpProcessInformation);

但是如果我尝试为 lpProcessAttributes 参数或 lpThreadAttributes 参数传递 null,我会得到一个编译器错误:

Error 2 Argument 3: cannot convert from '<null>' to 'ref Debugging.Wrappers.SECURITY_ATTRIBUTES'

如何修改上述函数签名,以便我可以只为 SECURITY_ATTRIBUTES 参数传递 null,而不会出现此编译器错误? (如果我愿意,还可以传递一个真实的结构吗?)

最佳答案

好吧,我终于(!)找到了一个更好的方法:

将 SECURITY_ATTRIBUTES 声明为类而不是结构,并且不要通过 ref 传递它。 :-)

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool CreateProcess(
        string lpApplicationName,
        StringBuilder lpCommandLine,
        SECURITY_ATTRIBUTES lpProcessAttributes,
        SECURITY_ATTRIBUTES lpThreadAttributes,
        bool bInheritHandles,
        CreateProcessFlags dwCreationFlags,
        IntPtr lpEnvironment,
        string lpCurrentDirectory,
        STARTUPINFO lpStartupInfo, /// Required
        PROCESS_INFORMATION lpProcessInformation //Returns information about the created process
        );

/// <summary>
/// See http://msdn.microsoft.com/en-us/library/aa379560(v=VS.85).aspx
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
    public uint nLength;
    public IntPtr lpSecurityDescriptor;
    [MarshalAs(UnmanagedType.Bool)] public bool bInheritHandle;
}

好处:这还可以让您在 SECURITY_ATTRIBUTES 上声明一个不错的构造函数,它初始化 nLength。

关于c# - P/invoke 函数采用指向结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3183437/

相关文章:

c++ - "Unresolved external _WinMain@16"如果我将 WndProc 移动到另一个 cpp 文件

java - 将 Kotlin IntArray 转换为 ValueAnimator 所需的 Java Object[]

windows-services - Powerpoint Interop 在 Windows 服务中失败,但在 Windows 窗体应用程序中工作正常

c# - 为什么 NHibernate 需要 "protected internal"自动属性的可见性?

C#高速数据记录数据处理

c++ - 如何单独处理子ListBox WndProc?

winapi - 所有调整大小操作的 Windows 消息

c# - 可以为 C++ 应用程序编写 C# DLL(插件)吗?

c# - 我如何使用 LINQ 将这个父子对象模型投影到一个平面的单个对象中?

C# 泛型 & 不会发疯