P/invoke 函数采用指向结构的指针[重复]

2024-05-21

功能如创建进程 http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx有带有指向结构的指针的签名。在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);

但如果我尝试通过null为了lpProcessAttributes论证或lpThreadAttributes参数,我收到编译器错误:

错误 2 参数 3:无法从 '' 转换为 'ref 调试.Wrappers.SECURITY_ATTRIBUTES'

我怎样才能修改上面的函数签名以便我可以通过null对于 SECURITY_ATTRIBUTES 参数,没有此编译器错误? (如果我愿意的话,还可以传递一个真实的结构?)


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

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

    [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。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

P/invoke 函数采用指向结构的指针[重复] 的相关文章

随机推荐