【问题标题】:How Define Callback Func Inside Of Calling Method?如何在调用方法内部定义回调函数?
【发布时间】:2013-07-15 11:52:50
【问题描述】:

我想在调用方法中声明/定义我的委托和回调函数。那可能吗 ?如果是怎么办?这是我要执行我的第一次植入操作的代码:

delegate bool myDelegate(IntPtr module, string type, IntPtr lParam);

public static bool EnumResTypeProc(IntPtr module, string typename, IntPtr lParam)
{
    (((GCHandle) lParam).Target as List<string>).Add(typename);
    return true;
}

public static string[] getResourceTypes(IntPtr module)
{
    List<string> result = new List<string>();
    GCHandle pin = GCHandle.Alloc(result);
    WinApi.EnumResourceTypes(module, Marshal.GetFunctionPointerForDelegate(new myDelegate(EnumResTypeProc)), (IntPtr)pin);
    pin.Free();
    return result.ToArray();
}


我得到的最接近:
delegate bool myDelegate(IntPtr module, string type, IntPtr lParam);

public static string[] getResourceTypes(IntPtr module)
{
    List<string> result = new List<string>();
    GCHandle pin = GCHandle.Alloc(result);
    myDelegate d = delegate(IntPtr handle, string typename, IntPtr lParam)
        { (((GCHandle) lParam).Target as List<string>).Add(typename); return true; };
    WinApi.EnumResourceTypes(module, Marshal.GetFunctionPointerForDelegate(d), (IntPtr) pin);
    pin.Free();
    return result.ToArray();
}


此时在方法中声明委托是not possible。即使编译它也会导致非托管代码使我的应用程序崩溃。

【问题讨论】:

    标签: c# winapi delegates lambda callback


    【解决方案1】:

    是的,您可以使用匿名方法lambda表达式

    // untested
    Func<IntPtr, string, IntPtr, bool> inline = (module, typename, lParam) =>
    {
        (((GCHandle)lParam).Target as List<string>).Add(typename);
        return true;
    };
    
    WinApi.EnumResourceTypes(module, Marshal.GetFunctionPointerForDelegate(inline), (IntPtr)pin);
    

    【讨论】:

    • 我会避免类型规范和参数。 LHS 会做的,不是吗?
    • 看起来很有希望。但不起作用。第一个 Action 必须是 Func。然后编译正常,但在调用时崩溃。不确定,但需要关键字delegate
    • 好吧,就像我说的:未经测试。您通过运行它使保修失效。
    • @nawfal 查看原始帖子 + 编辑。两个版本都可以正常工作。尝试在我的方法中声明委托似乎会导致崩溃。
    • @nawfal 我会试试的。也许很重要:应用程序在非托管代码中崩溃。所以我没有例外。
    【解决方案2】:

    【讨论】:

      【解决方案3】:

      或者我的例子:

      public delegate void AsyncMethodCaller(strind inputdata);
      
      
       void someMethod()
      {
      //
      // ... some actions 
      //
      AsyncMethodCaller caller = new AsyncMethodCaller(this.ProcessInputData);
      
         // Initiate the asychronous call.
         IAsyncResult result = caller.BeginInvoke("my data");
      }
      
      void ProcessInputData(string inputData)
      {
          // some actions
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多