How to use Delegates
Closed this issue · 2 comments
Hi!
I would really like to use Delegates and I am not sure how to do it in Boo.
My goal is to call unmanaged functions having their return type, their params and a pointer to them in unmanaged memory (like a DLL).
Here there is an example on how I use them in C#:
First, I define the delegate:
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate NTSTATUS NtCloseDelegate(
IntPtr ObjectHandle
);
Then, having a pointer to this function, I call it using the delegate:
// memAddr is a pointer to unmanaged memory where NtClose is defined.
NtCloseDelegate assembledFunction = (NtCloseDelegate)Marshal.GetDelegateForFunctionPointer(memAddr, typeof(NtCloseDelegate));
NTSTATUS result = (NTSTATUS)assembledFunction(MyObjectHandle);
That's it!
I searched the repo how to use delegates and all I could find is this way to create a delegate:
myDelegate as Delegate
I also searched the Wiki but couldn't find any references. (If I succeed, I would love to write an entry on the Wiki on how to use Delegates)
Thank you in advance! 😄
Much like how in C#, you define a delegate type as a method signature with the delegate
keyword, in Boo you define it with the callable
keyword. Thus:
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public callable NtCloseDelegate(ObjectHandle as IntPtr) as NTSTATUS
And then you use Marshal.GetDelegateForFunctionPointer
as usual, except it's probably better to use the Generic version rather than casting:
var assembledFunction = Marshal.GetDelegateForFunctionPointer[of NtCloseDelegate](memAddr)
Amazing! It works!
Thank you so much for the quick answer! 😄