P/Invoke

P/Invoke

P/Invoke (aussi appelé Platform Invocation Services) de Microsoft est une spécification de l'implémentation de CLI, qui permet au managed code d'appeler du code natif dans les DLL. Le code natif est référencé via les meta-données qui décrivent les fonctions exportées d'une DLL.

Sommaire

Utilisation

Quand P/Invoke est utilisé, le CLR gère le chargement des DLL et le conversion des types en types CTS. Pour réaliser cela, le CLR effectue les étapes suivantes :

  • Localiser l'emplacement de la DLL qui contient la fonction recherchée
  • Charger la DLL en mémoire
  • Trouver l'adresse en mémoire de la fonction et ajouter ses arguments dans la Pile d'appel
  • Convertir les types de données de .NET en un autre type

P/Invoke est utile pour accéder à des DLL qui ne sont pas basées sur Microsoft .NET, notamment celles basées sur C ou C++.

Le ramasse-miettes ne fonctionne pas à l'intérieur de la Platform Invocation Service; de même, la vérification de la validité des types ne fonctionne plus. Par conséquent, le programmeur doit être rigoureux dans sa programmation, sinon il y aura des Erreur de segmentation ou, (plus insidieusement...) des Fuites de mémoire.

Si le programmeur se montre peu rigoureux sur la conversion de type, un mauvais alignement de données peut provoquer de gros problèmes.

Exemples

Le premier exemple montre comment obtenir la version d'une DLL particulière.

Le prototype de la fonction DllGetVersion dans l'API Windows :

HRESULT DllGetVersion
(
    DLLVERSIONINFO* pdvi
)

Code C# pour appeler la fonction DllGetVersion :

[DllImport("shell32.dll")]
static extern int DllGetVersion(ref DLLVERSIONINFO pdvi);



Le second exemple montre comment extraire une icône d'un fichier :

Le prototype de la fonction ExtractIcon :

HICON ExtractIcon
(      
    HINSTANCE hInst,
    LPCTSTR lpszExeFileName,
    UINT nIconIndex
);

Code C# pour appeler la fonction ExtractIcon :

[DllImport("shell32.dll")]
static extern IntPtr ExtractIcon(
    IntPtr hInst, 
    [MarshalAs(UnmanagedType.LPStr)] string lpszExeFileName, 
    uint nIconIndex);

L'exemple suivant plus complexe montre comment partager un évènement entre deux processus sur une plate-forme Windows

Le prototype de la fonction CreateEvent :

HANDLE CreateEvent(
    LPSECURITY_ATTRIBUTES lpEventAttributes,
    BOOL bManualReset,
    BOOL bInitialState,
    LPCTSTR lpName
);

Code C# pour créer l'objet évènement :

[DllImport("kernel32.dll", SetLastError=true)]
static extern IntPtr CreateEvent(
    IntPtr lpEventAttributes, 
    bool bManualReset,
    bool bInitialState, 
    [MarshalAs(UnmanagedType.LPStr)] string lpName);

Historique

Le prédécesseur de Platform Invocation Service

Microsoft avait réalisé sa propre Java Virtual Machine; l'interface entre le code Java et les DLL était réalisée par la bibliothèque J/Direct (voir (en) J/Direct). Cette bibliothèque n'est plus maintenue actuellement par Microsoft.

Voir aussi

Références externes


References



Wikimedia Foundation. 2010.

Contenu soumis à la licence CC-BY-SA. Source : Article P/Invoke de Wikipédia en français (auteurs)

Игры ⚽ Нужен реферат?

Regardez d'autres dictionnaires:

  • invoke — in‧voke [ɪnˈvəʊk ǁ ˈvoʊk] verb [transitive] LAW to use a law, principle etc to support a view or decision: • The seller of the goods invoked an exclusion clause in the guarantee. * * * invoke UK US /ɪnˈvəʊk/ verb [T] FORMAL ► …   Financial and business terms

  • Invoke — In*voke , v. t. [imp. & p. p. {Invoked}; p. pr. & vb. n. {Invoking}.] [F. invoquer, L. invocare; pref. in in, on + vocare to call, fr. vox voice. See {Voice}, and cf. {Invocate}.] To call on for aid or protection; to invite earnestly or solemnly; …   The Collaborative International Dictionary of English

  • invoke — in·voke /in vōk/ vt in·voked, in·vok·ing 1: to appeal to as furnishing authority or motive 2: to put into legal effect or call for the observance of: enforce invoking his Fifth Amendment privilege …   Law dictionary

  • invoke — [in vōk′] vt. invoked, invoking [ME invoken < MFr invoquer < L invocare < in , in, on + vocare, to call < vox, VOICE] 1. to call on (God, a god, a saint, the Muses, etc.) for blessing, help, inspiration, support, etc. 2. to resort to… …   English World dictionary

  • invoke — [v1] call upon adjure, appeal to, beg, beseech, call forth, conjure, crave, entreat, implore, importune, petition, plead, pray, request, send for, solicit, summon, supplicate; concept 48 invoke [v2] put into effect apply, call in, effect, enforce …   New thesaurus

  • invoke —   [engl.], aufrufen …   Universal-Lexikon

  • invoke — (v.) late 15c., from M.Fr. envoquer (12c.), from L. invocare call upon, implore, from in upon (see IN (Cf. in ) (2)) + vocare to call, related to vox (gen. vocis) voice (see VOICE (Cf. voice)). Related …   Etymology dictionary

  • invoke — ► VERB 1) appeal to as an authority or in support of an argument. 2) call on (a deity or spirit) in prayer or as a witness. 3) call earnestly for. 4) summon (a spirit) by charms or incantation. 5) give rise to; evoke. DERIVATIVES invoker noun …   English terms dictionary

  • invoke — 01. The priest [invoked] a blessing for the sick child. 02. Too many people [invoke] a passage of the Bible to justify their intolerance of those who are different. 03. The old witch [invoked] the help of evil spirits to destroy her enemy. 04. By …   Grammatical examples in English

  • invoke — invocable, adj. invoker, n. /in vohk /, v.t., invoked, invoking. 1. to call for with earnest desire; make supplication or pray for: to invoke God s mercy. 2. to call on (a deity, Muse, etc.), as in prayer or supplication. 3. to declare to be… …   Universalium

  • invoke — UK [ɪnˈvəʊk] / US [ɪnˈvoʊk] verb [transitive] Word forms invoke : present tense I/you/we/they invoke he/she/it invokes present participle invoking past tense invoked past participle invoked formal 1) to use a law or rule in order to achieve… …   English dictionary

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”