Domanda

Ho una funzione API nativa che sembra:

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

L'ho tradotto in C# come:

[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 funzione di callback sembra:

typedef VOID ( WINAPI *WLAN_NOTIFICATION_CALLBACK)(
  PWLAN_NOTIFICATION_DATA data,
  PVOID context
);

Immagino che la versione C# sembrerà qualcosa di simile:

public delegate void WLAN_NOTIFICATION_CALLBACK(
    IntPtr pWlanNotificationData, IntPtr pContext)

Essenzialmente ho due domande:

Un delegato è l'oggetto corretto da utilizzare per un metodo nativo che si aspetta un puntatore di funzione?

E in tal caso, questo chiamerà automaticamente il delegato in C# quando la notifica viene ricevuta?

È stato utile?

Soluzione

Sì, dovresti usare un delegato e sì, funzionerà bene.

Tuttavia, devi assicurarti che il GC non raccoglie l'istanza del delegato. (in genere mettendolo in un campo)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top