[Mono-devel-list] IntPtr versus Marshaling

Jonathan Pryor jonpryor at vt.edu
Thu Mar 18 17:53:29 EST 2004


On Thu, 2004-03-18 at 15:29, christopher.p.taylor at us.army.mil wrote:
> Which is the "better" of the two?  Granted "better" is kinda relative,
> but you can always write C functions to get/set data in the C
> structure and do another DllImport on that "glue lib". Is the IntPtr
> approach faster than marshaling (I'm assuming so)? 

Short answer: my free, "life-changing" (with apologies to jackson)
marshalling guide, "Everything you (n)ever wanted to know about
Marshalling (and were afraid to ask!)."  Available at:

		(backup in case monodoc is down.  Please be gentle to
		my server.)

Longer answer: the deal with IntPtr is that it isn't marshalled.  It's
blitted across, like an int or long.  (OK, this is still considered to
be marshalling, but compared to the *normal* structure marshalling
process, this is not worth considering.)

Furthermore, as my guide above points out, marshalling is only useful
when you know the entire structure layout.  If you're dealing with OO
code (which may have an unbounded number of sub-classes), marshalling
with structs/classes doesn't work, as you "slice" the objects, keeping
only the base class.  It's also a bitwise copy (when possible), which
can complicate the copying process.

In general, classes/structs should only be used for "simple" structures,
or for structures which are Plain Old Data (POD) -- that is, no funky
uses as base classes (whatever the language), or variable-length arrays
at the end of the structure (fun!), etc.

> Or is it done mainly in the event that some platform is doing strange
> things at the ABI level?

P/Invoke deals with the C ABI, so this shouldn't be the case.  In fact,
you *can't* avoid the C ABI (except for variations on a theme, such as
calling convention).  Case in point: you couldn't call a Pascal function
which was expecting to call a nested function from a higher scope.  Or
anything that doesn't use the Run Time Stack for parameter passing.

> Are there any advantages or disadvantages I'm not picking up on?

See the guide.  If you have any more questions, just ask me.

 - Jon

More information about the Mono-devel-list mailing list