views:

63

answers:

1

Hello All,

This question is related to my previous question - http://stackoverflow.com/questions/3632473/dynamically-running-a-dll-at-a-remote-windows-box First of all, thanks for all your helpful insights.

I have found a way to run a DLL at a remote machine.

Now what I am trying to do is as follows.
(1) send a DLL to the remote machine.
(2) send a command to the remote machine to run a function in the DLL.
A command may contain things like (a) DLL's location (2) function entry point (3) parameters.

The trouble is... in a given DLL, there could just be any functions with various return types and parameters.

Do you have any suggestions on how I could effectively bind a DLL function with unknown return types and unknown parameters? Should I just put a restriction on what kind of functions the remote machine can run?

Here is my code snippet in C#...

[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); 
A: 

You can use Func types

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

Once your delegate type is created you can use Marshal.GetDelegateForFunctionPointer http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getdelegateforfunctionpointer(VS.80).aspx

Edit: refer to this post http://stackoverflow.com/questions/773099/generating-delegate-types-dynamically-in-c

Ankit