使用C#对CreateProcess进行后期绑定会返回null值

时间:2015-08-26 18:34:20

标签: c# createprocess late-binding kernel32 argumentnullexception

我正在尝试对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;

2 个答案:

答案 0 :(得分:1)

kernel32.dll实际上并不导出名称为CreateProcess的函数入口点 - 它是CreateProcessA,或者是CreateProcessW的unicode(Wide)参数。

答案 1 :(得分:1)

kernel32中没有名为CreateProcess的函数。它存在两个版本CreateProcessA(ANSI)和CreateProcessW(Unicode)。您可以在按钮documentation for CreateProcess on MSDN处看到。

这不是CreateProcess所独有的几乎每个采用字符串的Win32 API函数都会有AW版本。

以下是您想要的:

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

另见What is the difference between CreateProcess and CreateProcessA?