2

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

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();
}


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

4

3 回答 3

2

是的,您可以使用匿名方法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);
于 2013-07-15T11:57:27.073 回答
0

尝试使用此链接:

微软支持

如何在 C# 和 .NET 中编写回调

于 2013-07-15T12:06:01.430 回答
0

或者我的例子:

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
}
于 2013-07-15T12:12:33.873 回答