I have an implementation building a delegate handler collection.
public class DelegateHandler
{
internal delegate object delegateMethod(object args);
public IntPtr PublishAsyncMethod(MethodInfo method, MethodInfo callback)
{
RuntimeMethodHandle rt;
try
{
rt = method.MethodHandle;
delegateMethod dMethod = (delegateMethod)Delegate.CreateDelegate
(typeof(delegateMethod), method.ReflectedType, method, true);
AsyncCallback callBack = (AsyncCallback)Delegate.CreateDelegate
(typeof(AsyncCallback), method.ReflectedType, callback, true);
handlers[rt.Value] = new DelegateStruct(dMethod, callBack);
return rt.Value;
}
catch (System.ArgumentException ArgEx)
{
Console.WriteLine("*****: " + ArgEx.Source);
Console.WriteLine("*****: " + ArgEx.InnerException);
Console.WriteLine("*****: " + ArgEx.Message);
}
return new IntPtr(-1);
}
}
I publish using the following:
ptr = DelegateHandler.Io.PublishAsyncMethod(
this.GetType().GetMethod("InitializeComponents"),
this.GetType().GetMethod("Components_Initialized"));
And the method I'm creating a delegate from:
public void InitializeComponents(object args)
{
// do stuff;
}
And the callback method:
public void Components_Initialized(IAsyncResult iaRes)
{
// do stuff;
}
Now, I've also already looked at this to get an idea of what I might be doing wrong. The CreateDelegate(...) is causing me to receive:
*****: mscorlib
*****:
*****: Error binding to target method.
What is wrong? The methods reside in a different, non-static public class. Any help would be greatly appreciated.
NOTE: These methods will have parameters and return values. As I understand Action, and Action<T>, this would not be an option.
There are 2 problems.
First, you are passing incorrect arguments to CreateDelegate. Since you are binding to instance methods, you need to pass the instance to which the delegates will be bound, but you are passing method.ReflectedType instead of a reference to an object of the class that declares InitializeComponents and Components_Initialized.
Second, the signature of InitializeComponents does not match the declaration of delegate dMethod. The delegate has an object return type yet InitializeComponents returns void.
The following should work:
// return type changed to void to match target.
internal delegate void delegateMethod(object args);
// obj parameter added
public static void PublishAsyncMethod(object obj, MethodInfo method, MethodInfo callback)
{
delegateMethod dMethod = (delegateMethod)Delegate.CreateDelegate
(typeof(delegateMethod), obj, method, true);
AsyncCallback callBack = (AsyncCallback)Delegate.CreateDelegate
(typeof(AsyncCallback), obj, callback);
}
DelegateHandler.PublishAsyncMethod(
this, // pass this pointer needed to bind instance methods to delegates.
this.GetType().GetMethod("InitializeComponents"),
this.GetType().GetMethod("Components_Initialized"));
Related
I have a problem, Test1 produces "System.ArgumentException : method argument length mismatch" while Test2 and Test3 passes fine. I need to subscribe to an event using reflection, everything works if I use simple methods, but when I get into lambdas, it stops working as expected.
Debugging shows for all lambdas that they are "Void <>m__0(Int32)" which is the correct type for event and the same as "eventInfo.EventHandlerType".
Why does it fail? Or maybe, how to workaround that?
Do c# add more arguments to a method which is created by lambda like in Test1?
::Complete code here:
public class A
{
public void Test1()
{
var str = "aa";
B.Subscribe(typeof(C), "myEvent", (int a) => { var any = str; }, null);
}
public void Test2()
{
B.Subscribe(typeof(C), "myEvent", (int a) => { var any = a; }, null);
}
public void Test3()
{
B.Subscribe<int>(typeof(C), "myEvent", callback, this);
}
public void callback(int a) { }
}
public static class B
{
public static void Subscribe<T>(Type type, string eventName, Action<T> callback, object target)
{
var eventInfo = type.GetEvent(eventName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
var handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, target, callback.Method);
eventInfo.AddEventHandler(null, handler);
}
}
public sealed class C
{
public static event Action<int> myEvent;
}
EDIT:
Apparently it's Mono bug. GetInvocationList()[0] to get the Delegate fixes the issue in above example.
But subscribing to event produces "System.InvalidCastException : Cannot cast from source type to destination type." If event is not of type Action but of custom delegate: (if class "C" is like that, it throws, if class "C" is like above, it passes fine)
public sealed class C
{
public static event MyDel myEvent;
public delegate void MyDel(int a);
}
Is it different issue? Edit #2, event expects MyDel type, but gets Action Int32. How can I convert from Action<T> to MyDel or better, to eventInfo.EventHandlerType, because I don't know what type of event there can be.
Actually, after further investigation I noticed that my target was bad.
For methods defined in class, class instance as target is okay.
For lambdas I thought it was null, at least it works with null, as long as it does not interfere with local variables defined inside the method where the lambda was created.
So Action has a property Target, using callback.Target in Delegate.CreateDelegate solves the issue.
The target for lambda actually holds a reference to the class instance and to the all local variables it touches (debugger shows it).
Strange that it worked on newest .NET, maybe a slight difference between mono and .NET.
Let's say I have a type, which I know to be derived from a Delegate type. I would like to create an object of this type wrapping an anonymous delegate that accepts arbitrary params and returns an object of correct return type:
var retType = type.GetMethod("Invoke").ReturnType;
var obj = Delegate.CreateDelegate(type, delegate(object[] args) {
...
if (retType != typeof(void))
... somehow create object of type retType and return it ...
});
Obviously this won't compile, because CreateDelegate expects a MethodInfo as the second argument. How can I do this correctly?
Update: A little more info on what I am trying to achieve. There are two applications running - client in a browser and a server in C#. Browser is able to call remote functions on the server side by serializing arguments to JSON and sending the call over the network (like in RPC). This works already, but I would like to add support for callbacks. For example:
JavaScript (client):
function onNewObject(uuid) { console.log(uuid); }
server.notifyAboutNewObjects(onNewObject);
C# (server):
void notifyAboutNewObjects(Action<string> callback) {
...
callback("new-object-uuid");
...
}
The middleware code will receive a call from the browser and will need to generate fake callback delegate that will actually send the call to callback back to the browser and block the thread until it completes. The code for sending/receiving is there already, I am just stuck on how to generate a generic delegate that will simply put all arguments into an array and pass them to the sending code.
Update: If someone can write code that will generate such a delegate at runtime (e.g. using DynamicMethod) , I'll consider that a valid answer. I just don't have enough time to learn how to do this and hope that someone experienced will be able to write this code quickly enough. Essentially the code should just take arbitrary delegate params (list and types are available at runtime), put them into an array and call generic method. The generic method will always return an object, which should be cast into respective return type or ignored if the function returns void.
Uppdate: I've created a small test program that demonstrates what I need:
using System;
using System.Reflection;
namespace TestDynamicDelegates
{
class MainClass
{
// Test function, for which we need to create default parameters.
private static string Foobar(float x, Action<int> a1, Func<string, string> a2) {
a1(42);
return a2("test");
}
// Delegate to represent generic function.
private delegate object AnyFunc(params object[] args);
// Construct a set of default parameters to be passed into a function.
private static object[] ConstructParams(ParameterInfo[] paramInfos)
{
object[] methodParams = new object[paramInfos.Length];
for (var i = 0; i < paramInfos.Length; i++) {
ParameterInfo paramInfo = paramInfos[i];
if (typeof(Delegate).IsAssignableFrom(paramInfo.ParameterType)) {
// For delegate types we create a delegate that maps onto a generic function.
Type retType = paramInfo.ParameterType.GetMethod("Invoke").ReturnType;
// Generic function that will simply print arguments and create default return value (or return null
// if return type is void).
AnyFunc tmpObj = delegate(object[] args) {
Console.WriteLine("Invoked dynamic delegate with following parameters:");
for (var j = 0; j < args.Length; j++)
Console.WriteLine(" {0}: {1}", j, args[j]);
if (retType != typeof(void))
return Activator.CreateInstance(retType);
return null;
};
// Convert generic function to the required delegate type.
methodParams[i] = /* somehow cast tmpObj into paramInfo.ParameterType */
} else {
// For all other argument type we create a default value.
methodParams[i] = Activator.CreateInstance(paramInfo.ParameterType);
}
}
return methodParams;
}
public static void Main(string[] args)
{
Delegate d = (Func<float, Action<int>,Func<string,string>,string>)Foobar;
ParameterInfo[] paramInfo = d.Method.GetParameters();
object[] methodParams = ConstructParams(paramInfo);
Console.WriteLine("{0} returned: {1}", d.Method.Name, d.DynamicInvoke(methodParams));
}
}
}
I wrote a opensource PCL library, called Dynamitey (in nuget), that does all sorts of dynamic things using the C# DLR. .
It specifically has a static method called Dynamic.CoerceToDelegate(object invokeableObject, Type delegateType) That basically wraps the dynamic invocation of a DynamicObject or a more general delegate, with the specific Type of delegate using CompiledExpressions (source).
using System.Dynamic you can create an invokable object:
public class AnyInvokeObject:DynamicObject{
Func<object[],object> _func;
public AnyInvokeObject(Func<object[],object> func){
_func = func;
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result){
result = _func(args);
return true;
}
}
Then in your sample:
var tmpObj = new AnyInvokeObject(args => {
Console.WriteLine("Invoked dynamic delegate with following parameters:");
for (var j = 0; j < args.Length; j++)
Console.WriteLine(" {0}: {1}", j, args[j]);
if (retType != typeof(void))
return Activator.CreateInstance(retType);
return null;
});
methodParams[i] = Dynamic.CoerceToDelegate(tmpObj, paramInfo.ParameterType);
You could either check out the source code for SignalR or simply just use it.
Register a function in browser that the server can call
var connection = $.hubConnection();
var yourHubProxy = connection.createHubProxy('yourHub');
yourHubProxy.on('addMessageToConsole', function (message) {
console.log(message);
});
and on the server
public class YourHub : Hub
{
public void SendMessage(string message)
{
Clients.All.addMessageToConsole(message);
}
}
See here for more examples.
How about a solution without delegates?
(warning: rampant pseudocode)
class AbstractServerToClientMessage {
public virtual string ToJSON();
}
class OnNewObjectMessage: AbstractServerToClientMessage {...}
class OnSomethingElseHappenedMessage: AbstractServerToClientMessage {...}
void NotifyClient(AbstractServerToClientMessage message)
event OnNewObject;
event OnSomethingElseHappened;
void notifyAboutNewObjects() {
...
OnNewObject += NotifyClient;
...
}
void AddNewObject(SomeObject obj) {
OnNewObjectMessage message(obj);
OnNewObject(message);
// actually add the object
}
messages will be serialized anyway, so why bother? Polymorphism will take care of the rest. The only requirement is to have a set of messages which correspond to each event type.
Returning the value may be implemented by writing to some field in the AbstractServerToClientMessage.
Or, you can actually have a delegate with a fixed signature accepting a similar AbstractServerToClientMessage. Again, polymorphism (+ a class factory for deserialization) will allow to cast it to correct type of message.
My code is as follows:
class PropertyRetrievalClass
{
public delegate object getProperty(string input);
public object get_Chart_1(string iput)
{
Console.WriteLine(iput);
return "";
}
public object get_Chart_2(string iput)
{
Console.WriteLine(iput);
return "";
}
public PropertyRetrievalClass() { }
}
public static void Main()
{
int i = 1;
PropertyRetrievalClass obj = new PropertyRetrievalClass();
Delegate del = Delegate.CreateDelegate(typeof(PropertyRetrievalClass), obj, "get_chart_" + i.ToString());
string output= del("asldkl");
}
It is giving me an error saying "error CS0118: 'del' is a 'variable' but is used like a 'method'"
What should I do to use this delegate? I want to call any of "get_chart_1" or "get_chart_2" function and both of them take a string input?
Thanks in advance...
You have two issues in your code.
A Delegate object is not a method, so you need to use a method on the Delegate object to invoke the method it refers
The first argument to CreateDelegate should be the delegate type, not the class containing a method you want to invoke.
Full working example:
public delegate void ParamLess();
class SomeClass
{
public void PrintStuff()
{
Console.WriteLine("stuff");
}
}
internal class Program
{
private static Dictionary<int, int> dict = null;
static void Main()
{
var obj = new SomeClass();
Delegate del = Delegate.CreateDelegate(typeof(ParamLess), obj,
"PrintStuff", false);
del.DynamicInvoke(); // invokes SomeClass.PrintStuff, which prints "stuff"
}
}
In your case, the Main method should look like this:
public static void Main()
{
int i = 1;
PropertyRetrievalClass obj = new PropertyRetrievalClass();
Delegate del = Delegate.CreateDelegate(
typeof(PropertyRetrievalClass.getProperty),
obj,
"get_Chart_" + i.ToString());
string output = (string)del.DynamicInvoke("asldkl");
}
Update
Note that CreateDelegate is case sensitive on the method name, unless you tell it not to.
// this call will fail, get_chart should be get_Chart
Delegate del = Delegate.CreateDelegate(
typeof(PropertyRetrievalClass.getProperty),
obj,
"get_chart_" + i.ToString());
// this call will succeed
Delegate del = Delegate.CreateDelegate(
typeof(PropertyRetrievalClass.getProperty),
obj,
"get_Chart_" + i.ToString());
// this call will succeed, since we tell CreateDelegate to ignore case
Delegate del = Delegate.CreateDelegate(
typeof(PropertyRetrievalClass.getProperty),
obj,
"get_chart_" + i.ToString(),
true);
The other answers have addressed the problem with your code, but I wanted to offer an alternative.
If there are a limited, finite number of methods that your retrieval class is choosing from, and they have the same signatures, this can be done much more efficiently without using reflection:
public int MethodIndex {get;set;}
public static void Main()
{
PropertyRetrievalClass obj = new PropertyRetrievalClass();
Func<string,object> getChartMethod;
switch(MethodIndex)
{
case 1:
getChartMethod = obj.get_chart_1;
break;
case 2:
getChartMethod = obj.get_chart_2;
break;
}
string output= getChartMethod("asldkl");
}
If there were a lot, you could just create an array instead of using a switch. Obviously you could just run the appropriate function directly from the switch, but I assume that the idea is you may want to pass the delegate back to the caller, and a construct like this lets you do that without using reflection, e.g.
public static Func<string,object> GetMethod
{
... just return getChartMethod directly
}
You are using the Delegate class not the delegate keyword.
You cannot call a method on Delegate type. You have to use DynamicInvoke() which is very slowwwwwww.
Try this:
string output = (string) del.DynamicInvoke(new object[]{"asldkl"});
You can only call delegates with method call syntax, if they have a known signature. You need to cast your delegate to the delegate type you defined earlier.
var del = (PropertyRetrievalClass.getProperty)Delegate.CreateDelegate(typeof(PropertyRetrievalClass.getProperty), obj, "get_Chart_" + i.ToString());
You also need to change the first argument to CreateDelegate, because it should be the delegate type. And capitalize the "C" in "get_Chart_".
And then, you will need to cast the returned object to string:
string output= (string) del("asldkl");
Or change the delegate type and the methods to have string as their return type.
I have the following code:
class Program
{
static void Main(string[] args)
{
new Program().Run();
}
public void Run()
{
// works
Func<IEnumerable<int>> static_delegate = new Func<IEnumerable<int>>(SomeMethod<String>);
MethodInfo mi = this.GetType().GetMethod("SomeMethod").MakeGenericMethod(new Type[] { typeof(String) });
// throws ArgumentException: Error binding to target method
Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), mi);
}
public IEnumerable<int> SomeMethod<T>()
{
return new int[0];
}
}
Why can't I create a delegate to my generic method? I know I could just use mi.Invoke(this, null), but since I'm going to want to execute SomeMethod potentially several million times, I'd like to be able to create a delegate and cache it as a small optimization.
You method isn't a static method, so you need to use:
Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), this, mi);
Passing "this" to the second argument will allow the method to be bound to the instance method on the current object...
All of the Func delegates return a value. What are the .NET delegates that can be used with methods that return void?
All Func delegates return something; all the Action delegates return void.
Func<TResult> takes no arguments and returns TResult:
public delegate TResult Func<TResult>()
Action<T> takes one argument and does not return a value:
public delegate void Action<T>(T obj)
Action is the simplest, 'bare' delegate:
public delegate void Action()
There's also Func<TArg1, TResult> and Action<TArg1, TArg2> (and others up to 16 arguments). All of these (except for Action<T>) are new to .NET 3.5 (defined in System.Core).
... takes no arguments and has a void return type?
I believe Action is a solution to this.
All of the Func delegates take at least one parameter
That's not true. They all take at least one type argument, but that argument determines the return type.
So Func<T> accepts no parameters and returns a value. Use Action or Action<T> when you don't want to return a value.
Try System.Func<T> and System.Action
A very easy way to invoke return and non return value subroutines. is using Func and Action respectively. (see also https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx)
Try this this example
using System;
public class Program
{
private Func<string,string> FunctionPTR = null;
private Func<string,string, string> FunctionPTR1 = null;
private Action<object> ProcedurePTR = null;
private string Display(string message)
{
Console.WriteLine(message);
return null;
}
private string Display(string message1,string message2)
{
Console.WriteLine(message1);
Console.WriteLine(message2);
return null;
}
public void ObjectProcess(object param)
{
if (param == null)
{
throw new ArgumentNullException("Parameter is null or missing");
}
else
{
Console.WriteLine("Object is valid");
}
}
public void Main(string[] args)
{
FunctionPTR = Display;
FunctionPTR1= Display;
ProcedurePTR = ObjectProcess;
FunctionPTR("Welcome to function pointer sample.");
FunctionPTR1("Welcome","This is function pointer sample");
ProcedurePTR(new object());
}
}
Occasionally you will want to write a delegate for event handling, in which case you can take advantage of System.EvenHandler<T> which implicitly accepts an argument of type object in addition to the second parameter that should derive from EventArgs. EventHandlers will return void
I personally found this useful during testing for creating a one-off callback in a function body.
... takes no arguments and has a void return type?
If you are writing for System.Windows.Forms, You can also use:
public delegate void MethodInvoker()