[Mono-list] PInvoke Conventions

Rhys Weatherley rweather@zip.com.au
Sat, 28 Jul 2001 09:16:17 +1000


OK, reality check time.  I think that the people that are
suggesting generating C stubs and C# definitions to
handle the "nasty bits" are missing the whole point
behind PInvoke.

There are two primary mechanisms in the CLI for invoking
native method code: internalcall and PInvoke.

The "internalcall" mechanism is used mainly for methods
that live very close to the VM.  As such, they use the same
calling and parameter passing mechanisms as regular
C# code.

If there is a "semantic mismatch" between the parameters
in the C# world and those in the native world, then the
internalcall method itself is reponsible for unpacking the
C# data and converting it into whatever the native
world requires.  This wrapper layer will normally be
written by the programmer, or by tools that the
programmer writes.

The suggestion of building C wrappers that automatically
convert between the two worlds is what is needed to wrap
a C function to be invoked as "internalcall".

PInvoke is something completely different.  Rather than
requiring the programmer to write the wrapper (either
directly, or indirectly through a tool), PInvoke builds the
wrapper on the fly at runtime from a list of metadata
instructions, supplied as attributes.

PInvoke is very handy for people writing .NET applications.
Let's say Fred is writing a database app and needs to call
some nifty piece of business logic written by some other
group in C.  Being an SQL/dbscript monkey, Fred is not
terribly bright when it comes to C stuff.

With internalcall, he has to drop down to the native level
and invoke some serious black magic.  With PInvoke, he
writes a 1-line description of the C parameters, and the
VM performs the black magic for him.

If we go the route that some people suggesting, then we
might as well forget PInvoke altogether and just use
"internalcall".

PInvoke is hard.  Damned hard.  It cannot be made easy,
because it is performing a monstrous amount of black
magic behind the scenes.  But that black magic is useful
because then people using the platform don't need to
concern themselves with it.

The trick is coming up with a *standard* way of doing
this black magic.  I fear that if the "C wrapper" crowd
wins this war, then the resulting C# library will only work
with Mono's VM and the rest of us will have to start
from scratch.

Cheers,

Rhys.