使用C#对CreateProcess进行后期绑定时返回空值

使用C#对CreateProcess进行后期绑定时返回空值,c#,createprocess,late-binding,kernel32,argumentnullexception,C#,Createprocess,Late Binding,Kernel32,Argumentnullexception,我试图在kernel32.dll中的CreateProcess函数上使用后期绑定,但是,它返回的值与任何其他函数不同 下面是我用于后期绑定的代码 public abstract class LateBinding { [DllImport("kernel32.dll", CharSet = CharSet.Auto, BestFitMapping = false, SetLastError = true), SuppressUnmanagedCodeSecurity()] pri

我试图在kernel32.dll中的CreateProcess函数上使用后期绑定,但是,它返回的值与任何其他函数不同

下面是我用于后期绑定的代码

public abstract class LateBinding
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, BestFitMapping = false, SetLastError = true), SuppressUnmanagedCodeSecurity()]
    private static extern LBHandle LoadLibrary(string fileName);

    [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity()]
    private static extern IntPtr GetProcAddress(LBHandle hModule, string procname);

    private Delegate Result = default(Delegate);

    public Delegate Call(string library, string method, Type type)
    {
        LBHandle Lib = LoadLibrary(library);
        if (!Lib.IsInvalid && !Lib.IsClosed)
        {
            Result = Marshal.GetDelegateForFunctionPointer(GetProcAddress(Lib, method), type);                
            Lib.Close();
        }
        return Result;
    }
}

[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public sealed class LBHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool FreeLibrary(IntPtr hModule);

    private LBHandle() : base(true) { }

    protected override bool ReleaseHandle()
    {
        return FreeLibrary(handle);
    }
}
这就是我调用函数的方式

private delegate bool dCreateProcess(string applicationName, string commandLine, IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUP_INFORMATION startupInfo, ref PROCESS_INFORMATION processInformation);
dCreateProcess CreateProcess = Call("kernel32.dll", "CreateProcess", typeof(dCreateProcess)) as dCreateProcess;

kernel32.dll
实际上并没有导出名为
CreateProcess
的函数入口点-它要么是
CreateProcessA
,要么是unicode(宽)参数的
CreateProcessW

在kernel32中没有名为
CreateProcess
的函数。它有两个版本
CreateProcessA
(ANSI)和
CreateProcessW
(Unicode)。你可以在按钮上看到

这并不是
CreateProcess
所独有的,几乎每个接受字符串的Win32 API函数都有
a
W
版本

以下是您想要的:

dCreateProcess CreateProcess = Call("kernel32.dll", "CreateProcessW", typeof(dCreateProcess)) as dCreateProcess;

另请参见

LoadLibrary
返回一个作为模块句柄的
IntPtr
,不确定如何将其展开到该类中,或者它是否以这种方式工作。您是否尝试过查看运行后的最后一个错误是什么?您已将last error设置为true,因此应该能够检查它。请检查:在调用完函数之前,您也不应该调用
FreeLibrary
FreeLibrary
将从进程中卸载DLL。你看不出kernel32有什么问题,因为它已经被加载了,但是如果你在调用
FreeLibrary
后调用了一个用户Dll函数,你就会崩溃。看来这一直都是问题所在,谢谢你向我澄清。