[Mono-list] PInvoke Conventions

Rhys Weatherley rweather@zip.com.au
Thu, 19 Jul 2001 10:10:35 +1000


Bob Salita wrote:

> Rhys previously posted the struct problem example, which poisons many
> seemingly good solutions. Hmmm, but wait, a struct is so C compiler specific
> that there can be no hope of a generalized C#-to-C-struct mapping. Several
> 32/32 compilers on the same system can map a struct totally differently.
> Thus I'm concluding that there is no way to reliably handle structs.

Actually, "libffi" does a pretty good job of handling structs, both in
parameters and return values.  The main issue is one of layout of
the C#-defined class, but it may be possible to hijack some of
"libffi"'s code to handle this also, if an appropriate attribute is
present to turn the special layout on.  e.g.

[NativeStructLayout(true), NativeTypeSizes(true)]
public struct timeval
{
    public long tv_sec;
    public long tv_usec;
}

It may not be necessary to add an extra attribute either.  The
CLR spec already has a way to specify that a class has "explicit
layout".  Right now, it assumes that the programmer will provide
the offsets of the fields and the packing details to use for the
class.  Sam, perhaps it could be adjusted slightly to say "if the
class is marked explicit, but no explicit information is supplied,
then use the platform-specific conventions".

The "libffi" library is quite nice.  It takes care of all the nasty
business of converting abstract descriptions of call information
into the specifics used by the underlying CPU, OS, and compiler.

Cheers,

Rhys.