微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – P / invoke函数获取指向struct 的指针

参见英文答案 > How do I handle null or optional dll struct parameters in C#1个
诸如 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,而不会出现此编译器错误? (如果我愿意,还能传递一个真正的结构?)

解决方法

null仅对.Net中的引用类型有效.您的Security_ATTRIBUTES是一个结构,它是一个ValueType.您需要传递一个空的Security_ATTRIBUTES结构,而不是传递null. (在你的电话中说新的Security_ATTRIBUTES()).

一个更干净的方法是向你的struct添加一个静态Empty属性,然后只传递Security_ATTRIBUTES.Empty

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

    public static Security_ATTRIBUTES Empty {
        get {
            return new Security_ATTRIBUTES {
                nLength = sizeof(int)*2 + IntPtr.Size,lpSecurityDescriptor = IntPtr.Zero,bInheritHandle = 0,};
        }
    }
}

或者更好的是,不是使用P / Invoke创建进程,而是检查System.Diagnostics.Process类,它应该可以满足您的需要.

原文地址:https://www.jb51.cc/csharp/239180.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐