[Mono-devel-list] IntPtr versus Marshaling

Marcus mathpup at mylinuxisp.com
Thu Mar 18 11:50:44 EST 2004

IntPtr provides an opaque pointer to the data. You cannot directly access the 
information pointed to using an IntPtr. Most of the decision of whether to 
use IntPtr or to match the structure layout depends on whether it is 
necessary to "dig inside" the data structure from managed code.

If the library you're using with P/Invoke provides accessor functions for the 
data, it's easier simply to use IntPtr. For example, if your C library has 
something like this

	int value;
	char* name;
} Structure;

Structure* newStructure() { ... }
int getValue(Structure* structure) { ... }
char* getName(Structure* structure { ... }

You will probably never need to dig inside the struct Structure. On the other 
hand, if the getValue and getName functions were not present, and you needed 
to access the fields inside Structure, you might want to create a C# class to 
mirror the C layout.

The other problem is probability.You are tying your C# code to the C code in 
the sense that any changes to the layout of the C struct will require 
changing your code. (C programs will just #include the header that defines 
the struct, so they will not have problems.) There's also the issue of 
platform independence. Unlike C#, C types can vary from platform to platform.

On Thursday 18 March 2004 8:29 pm, christopher.p.taylor at us.army.mil wrote:
> Hey everyone I've a `burning` question about marshaling and IntPtr's,
>  So I'm writing a binding for a C lib on gnu/linux and I've been using the
> Cairo bindings as my guide. I noticed in Cairo#, Duncan used IntPtr for all
> references to the C structure. I noticed you can also Marshal classes and
> structs by defining them and then using a StructLayout attribute to get the
> structure into a more "natural form" instead of making calls to an IntPtr.
> 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)? Or is it done mainly in the event that some
> platform is doing strange things at the ABI level? Are there any advantages
> or disadvantages I'm not picking up on?

More information about the Mono-devel-list mailing list