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类,它应该可以满足您的需要.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...