export table contains only names & relative addresses of symbols
does not indicate whether exported symbol is a function or global variable
does not indicate “shape” of functions (its signature) or variables (its type)
The partnership
programmer describes function location & signature in terms of CLR types
managed compiler produces assembly/type metadata that drives JIT compilation
JIT compiler uses metadata to build “stubs” that perform CLR/Win32 transition
load the requested DLL (LoadLibrary)
locate the target function in memory (GetProcAddress)
marshal parameters to/from the target function
P/Invoke Mechanics
The CLR/Win32 transition is carried out by stubs & helpers
stubs are little chunks of native code emitted by the JIT compiler
specific to the marshaling requirements dictated by the p/invoke declaration
helpers are native functions typically found in mscor*.dll
general purpose functions that don’t need to be tuned specifically to the target
examples:
convert a CLR System.String parameter into NUL-terminated ANSI string
given a collection of CAS (code access security) permissions, perform a demand/assert/etc
P/Invoke Metadata
Programmer-supplied metadata drives P/Invoke
Method prototype describes the native function in terms of CLR types
managed compiler emits metadata for the managed method (empty body)
managed method can be called like any other static method
JIT compiler uses metadata to load DLL and locate the exported method
JIT compiler uses metadata to build stubs that handle the transition
using System.Runtime.InteropServices;
internalclassProgram
{
staticvoidMain()
{
int sum = Add(2, 2);
}
[DllImport("nativecalc.dll")]
privatestaticexternintAdd(int a, int b);
}
P/Invoke Fine Tuning
Stub generation can be fine-tuned as needed
Using properties of DllImportAttribute
EntryPoint
CharSet
SetLastError
Others
By applying additional attributes to parameters and/or types
MarshalAsAttribute
StructLayoutAttribute
Lets you control the physical layout of the data fields of a class or structure