Chapter 12 showed you how to use Platform Invoke to call unmanaged functions defined in dynamic-link libraries (DLLs). For simple functions, the procedures outlined in the previous chapter will work very well, but you will come across cases that demand more advanced techniques.
This chapter will show you how to use unmanaged functions that take string arguments or array arguments, or require pointers to be passed. It will also show you how to pass pointers to managed objects into unmanaged code, and how to specify the path to a Platform Invoke DLL dynamically.
You use this attribute to specify how data should be marshaled between managed and unmanaged code when you need to override the defaults. When you're passing a string to a COM method, the default conversion is to a COM BSTR; when you're passing a string to a non-COM method using Platform Invoke, the default conversion is to a C-style LPSTR . For example, if you want to pass a C-style null- terminated string to a COM method, you will need to use MarshalAs to override the default conversion.
You can attach the MarshalAs attribute to method parameters and return values, and you always need to specify the type that is to be used for marshaling. The type to be used is represented by a member of the UnmanagedType enumeration, whose possible values are shown in Table 13-1.
The MarshalAs attribute is used in two different scenarios: interacting with COM components using COM interop, and calling unmanaged functions using Platform Invoke. Some of the members listed in the following table will be relevant only to one or other of these scenarios.
The MarshalAs attribute can be applied to a parameter like this:
The attribute instructs the interop marshaler to marshal the string object as an ANSI null-terminated string.