What is marshalling and how does it work?

Asked

Viewed 1,187 times

4

I’ve been working with a device that I sent to my software some information, but this information came in the type IntPtr, to read them, I had to use the class Marshal of . NET.

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

1 answer

3


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

Especially on . NET is used for communication with WITH which is the basis of a lot of stuff in Windows. It’s also widely used when using unmanaged code in general (called native, although the term is misleading). Another example is PRC.

There is a special treatment for pointers that obviously cannot be copied directly, it is necessary to indicate that it is a reference to another object that can already exist where it will be received or need to send 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, as required by COM, for example. Unmanaged code has several own types that do not exist in .NET. Through the marshalling it is possible to access the data on the managed side consistently.

what happens when I convert a IntPtr for String using the class Marshal?

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

You can understand a lot of what I’m talking about in class Marshall. And also that it is nothing simple and it takes good programming mastery, operating system operation, native code, etc. But virtually no one needs to use this. It’s like the unsafe, it is good to have, but it is for very restricted use, what alias is common Marshal work with unsafe.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.