【问题标题】:Dynamically binding a DLL function with unknown return types and parameters动态绑定具有未知返回类型和参数的 DLL 函数
【发布时间】:2010-09-07 05:39:31
【问题描述】:

这个问题和我之前的问题有关——dynamically running a DLL at a remote Windows box? 首先,感谢您提供的所有有用的见解。

我找到了一种在远程机器上运行 DLL 的方法。

现在我要做的是如下。
(1) 向远程机器发送一个DLL。
(2)向远程机器发送命令以运行DLL中的函数。
命令可能包含诸如 (a) DLL 的位置 (2) 函数入口点 (3) 参数之类的内容。

问题是......在给定的 DLL 中,可能只有具有各种返回类型和参数的任何函数。

对于如何有效地绑定具有未知返回类型和未知参数的 DLL 函数,您有什么建议吗?我应该限制远程机器可以运行什么样的功能吗?

这是我在 C# 中的代码 sn-p...

[DllImport("kernel32")]
public extern static IntPtr LoadLibrary(string dllToLoad);

[DllImport("kernel32")]
public extern static Boolean FreeLibrary(IntPtr hModule);

[DllImport("kernel32")]
public extern static IntPtr GetProcAddress(IntPtr hModule, string procedureName);

// THIS IS THE PART THAT I HAVE A PROBLEM WITH.
// Since I want to bind MyFunction to just about any function in a DLL, I sure cannot declare the following as something like "double". 
// Also there could just be any combinations of parameters (e.g. int, string, double..) 
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate double MyFunction(int arg); 

【问题讨论】:

    标签: c# dll unmanaged dllimport


    【解决方案1】:

    你可以使用 Func 类型

    public delegate TResult Func<TResult>();
    public delegate TResult Func<T, TResult>(T arg);
    public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
    public delegate TResult Func<T1, T2, T3, TResult>
        (T1 arg1, T2 arg2, T3 arg3);
    public delegate TResult Func<T1, T2, T3, T4, TResult>
        (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
    

    创建委托类型后,您可以使用 Marshal.GetDelegateForFunctionPointer http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getdelegateforfunctionpointer(VS.80).aspx

    编辑: 参考这篇文章 Generating Delegate Types dynamically in C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多