【发布时间】:2015-08-26 18:34:19
【问题描述】:
我正在尝试对 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;
【问题讨论】:
-
LoadLibrary返回一个IntPtr,它是模块的句柄,不确定您是如何将其解包到该类中的,或者它是否以这种方式工作。您是否尝试过查看运行后的最后一个错误是什么?您已将最后一个错误设置为 true,因此您应该能够检查它。 -
看看这个:link
标签: c# createprocess late-binding kernel32 argumentnullexception