and*_*rsh 2 c# dll pinvoke unmanaged marshalling
一般来说,我需要能够从我在编译时不知道的任何 DLL 中调用任何非托管函数。
我看到的所有文章(例如https://blogs.msdn.microsoft.com/jonathanswift/2006/10/03/dynamically-calling-an-unmanaged-dll-from-net-c/)都建议使用委托,但我在编译时不知道我要调用哪个函数,甚至不知道它需要哪些参数和多少参数。
基本上我有一个用户输入,如:调用“Kernel32.dll”函数“DeleteFile”参数[“C:\testfile.txt”]。
你能建议至少如何谷歌吗?“动态”这个词没有帮助..
任务本身有点疯狂,因为它实际上是一个大学项目。不确定它在现实生活中是否有用..
var dll = "kernel32.dll";
var fun = "DeleteFile";
var args = new object[] { "C:\\dev\\test.txt" };
IntPtr pDll = NativeMethods.LoadLibrary(dll);
IntPtr pFun = NativeMethods.GetProcAddress(pDll, fun);
// How can I call it in a different way, without having a delegate?
Marshal.GetDelegateForFunctionPointer(pFun, typeof(?????));
Run Code Online (Sandbox Code Playgroud)
我也同意 Roslyn 的想法,但是当我看到"Dynamic"和"P/Invoke" 时,我会想到好老 System.Reflection.Emit:
var asmName = new AssemblyName("Win32");
var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
var modBuilder = asmBuilder.DefineDynamicModule("Win32", emitSymbolInfo: false);
var typeBuilder = modBuilder.DefineType("Win32.User32", TypeAttributes.Class | TypeAttributes.Public);
// Optional: Use if you need to set properties on DllImportAttribute
var dllImportCtor = typeof(DllImportAttribute).GetConstructor(new Type[] { typeof(string) });
var dllImportBuilder = new CustomAttributeBuilder(dllImportCtor, new object[] { "user32.dll" });
var pinvokeBuilder = typeBuilder.DefinePInvokeMethod(
name: "ShowMessageBox",
dllName: "user32.dll",
entryName: "MessageBoxW",
attributes: MethodAttributes.Static | MethodAttributes.Public,
callingConvention: CallingConventions.Standard,
returnType: typeof(int), // typeof(void) if there is no return value.
// TODO: Construct this array from user input somehow:
parameterTypes: new Type[] { typeof(IntPtr), typeof(string), typeof(string), typeof(uint) },
nativeCallConv: CallingConvention.Winapi,
nativeCharSet: CharSet.Unicode);
pinvokeBuilder.SetCustomAttribute(dllImportBuilder);
Type user32Type = typeBuilder.CreateType();
const uint MB_YESNOCANCEL = 3;
user32Type
.GetMethod("ShowMessageBox", BindingFlags.Static | BindingFlags.Public)
// TODO: User input goes here:
.Invoke(null, new object[] { IntPtr.Zero, "Message Text", "Message Caption", MB_YESNOCANCEL });
Run Code Online (Sandbox Code Playgroud)
不漂亮,我知道。只是我的 0.02 美元。
警告:如果这段代码将在长时间运行的应用程序中被多次调用,请考虑AppDoman每次创建一个新的,并在调用完成时处理它;因为这是卸载生成的动态程序集的唯一方法。
| 归档时间: |
|
| 查看次数: |
1080 次 |
| 最近记录: |