Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
class Foo
{
    [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    public delegate void TestMethod(uint cap);
    public static TestMethod Method;

    static Foo()
    {
        Method = Func<TestMethod>("TestMethod");
    }

    public static T Func<T>(string name) where T : class
    {
        IntPtr _dll = IntPtr.Zero;// ptr to dll

        IntPtr ptr = GetProcAddress(_dll, name);

        Delegate a = Marshal.GetDelegateForFunctionPointer(ptr, typeof(T));

        //Create delegate of type T but with different body of a => { Console.WriteLine("test"); };
        Delegate b;
 
        //Multicast delegate
        return Delegate.Combine(a, b) as T;
    }
}


then

Foo.Method(); // executes the method and writes in console

The point is to wrap the T delegate and add functionality to it.

Can this be done ?
Posted
Updated 31-Oct-15 20:20pm
v8
Comments
phil.o 31-Oct-15 12:17pm    
Noy clear what you intend by combining delegates. Technically, delegates are method pointers. Nothing prevents you from using a delegate as a parameter for another delegate.
petarpetrovt 31-Oct-15 13:08pm    
my intention is to wrap a generic delegate and add functionality to it
phil.o 31-Oct-15 13:16pm    
I still don't understand. Please give a concrete example.
phil.o 31-Oct-15 13:40pm    
Please improve your question with the code. I don't read code in comments, they are not meant for that.
BillWoodruff 31-Oct-15 13:23pm    
If your generic method is based on T is a Class, how does returning two "combined" delegates make a Class to return ? Does not make sense ... to me. Please clarify.

1 solution

C#
delegate void EnclosingDelegate(string parameter);

delegate string EnclosedDelegate();

class foo
{
   void main() {
      EnclosedDelegate enclosed = () => "foo";
      EnclosingDelegate enclosing = (s) => s = enclosed();
   }
}

Is that what you are searching for?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900