¿Cómo implemento una devolución de llamada de la API nativa de Windows en C#?
Pregunta
Tengo una función de API nativa que se parece:
DWORD WINAPI WlanRegisterNotification(
__in HANDLE hClientHandle,
__in DWORD dwNotifSource,
__in BOOL bIgnoreDuplicate,
__in_opt WLAN_NOTIFICATION_CALLBACK funcCallback,
__in_opt PVOID pCallbackContext,
__reserved PVOID pReserved,
__out_opt PDWORD pdwPrevNotifSource
);
Lo he traducido a C# como:
[DllImport("Wlanapi.dll", EntryPoint = "WlanRegisterNotification")]
public static extern uint WlanRegisterNotification(
IntPtr hClientHandle, WLAN_NOTIFICATION_SOURCE dwNotifSource,
bool bIgnoreDuplicate, WLAN_NOTIFICATION_CALLBACK funcCallback,
IntPtr pCallbackContext, IntPtr pReserved,
[Out] out WLAN_NOTIFICATION_SOURCE pdwPrevNotifSource);
La función de devolución de llamada se ve como:
typedef VOID ( WINAPI *WLAN_NOTIFICATION_CALLBACK)(
PWLAN_NOTIFICATION_DATA data,
PVOID context
);
Supongo que la versión C# se verá algo así como:
public delegate void WLAN_NOTIFICATION_CALLBACK(
IntPtr pWlanNotificationData, IntPtr pContext)
Esencialmente tengo dos preguntas:
¿Es un delegado el objeto correcto a usar para un método nativo que espera un puntero de función?
Y si es así, ¿esto llamará automáticamente al delegado en C# cuando se reciba la notificación?
Solución
Sí, debe usar un delegado, y sí, funcionará bien.
Sin embargo, debe asegurarse de que el GC no recolecte su instancia de delegado. (Por lo general, poniéndolo en un campo)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow