A fairly common idiom in C is for functions taking a polymorphic closure to represent this as two arguments, a function pointer and void pointer (which is passed as one of the arguments to the function pointer.
An example taken from the GPGME library:
typedef gpgme_error_t (*gpgme_passphrase_cb_t) (void *hook,
const char *uid_hint,
const char *passphrase_info,
int prev_was_bad,
int fd);
void gpgme_set_passphrase_cb (gpgme_ctx_t ctx,
gpgme_passphrase_cb_t cb,
void *hook_value);
Conceptually, the function pointer plus void pointer represent the same thing as a delegate in C# (a closure). Is there a nice, canonical way to marshal a delegate when making this sort of P/Invoke call?
Is there a nice, canonical way to marshal a delegate when making this sort of P/Invoke call?
You don't need to use the void*
parameter because a C# delegate is a closure. Pass IntPtr.Zero
as the hook value. Your C# delegate still needs to accept the void*
parameter but it can simply ignore it since it does not need it.