What is marshalling and how does it work?

2

I was working with a device that sent some information to my software , but this information came in type IntPtr , to read it, I had to use the Marshal class .NET.

What is marshalling and what happens when I convert a IntPtr to String using the Marshal class?

    
asked by anonymous 24.03.2017 / 04:11

1 answer

2

Marshalling is similar to serialization, it is a technique of transforming a binary object suitable for memory into an object in a format suitable for transport between processes, possibly on different machines.

Especially in .NET it is used to communicate with COM which is the basis of many things in Windows. It is also widely used when using unmanaged code in general (called native, although the term is misleading ). Another example is RPC .

There is a special handling for pointers that obviously can not be copied directly, you have to indicate that it is a reference to another object that may already exist where it will be received or needs to be sent as well.

But in general the way the object is converted depends on implementation. It may be serialized even, but it may use some specific format and protocols of the technology used, such as that required by COM, for example. Unmanaged code has many unique types that do not exist in .NET. Through marshalling you can access the data on the managed side consistently.

  

What happens when I convert an IntPtr to String using the Marshal class?

It's not that you make a IntPtr into String , you can turn a "native" object that fits well into a string into this type of .NET, IntPtr is the indicator of where this is supposed to be string and probably it will serve as a reference for the string and which will be stored in a variable as if it were a string in> managed. Note that no conversion is required, only if the protocols are met. That is why, for example, String of .NET ends with a null even though text size is available early in the object, it is a matter of direct interoperability without conversions since C only understands null terminator .

Just to realize that I'm talking about the Marshall ". And also that it is not simple and you need good programming domain, operating system operating, native code, etc. But practically nobody needs to use it. It's like unsafe it's nice to have, but it's for very restricted use, which alias is common Marshal working with unsafe

    
26.03.2017 / 23:43