Marshaling Data with Platform Invoke 之二 Marshaling Strings (用时查阅)
Platform invoke copies string parameters, converting them from the .NET Framework format (Unicode) to the unmanaged format (ANSI), if needed. Because managed strings are immutable, platform invoke does not copy them back from unmanaged memory to managed memory when the function returns.
The following table lists marshaling options for strings, describes their usage, and provides a link to the corresponding .NET Framework sample.
String |
Description |
Sample |
---|---|---|
By value. |
Passes strings as In parameters. |
|
As result. |
Returns strings from unmanaged code. |
|
By reference. |
Passes strings as In/Out parameters using StringBuilder. |
|
In a structure by value. |
Passes strings in a structure that is an In parameter. |
|
In a structure by reference (char*). |
Passes strings in a structure that is an In/Out parameter. The unmanaged function expects a pointer to a character buffer and the buffer size is a member of the structure. |
|
In a structure by reference (char[]). |
Passes strings in a structure that is an In/Out parameter. The unmanaged function expects an embedded character buffer. |
|
In a class by value (char*). |
Passes strings in a class (a class is an In/Out parameter). The unmanaged function expects a pointer to a character buffer. |
|
In a class by value (char[]). |
Passes strings in a class (a class is an In/Out parameter). The unmanaged function expects an embedded character buffer. |
|
As an array of strings by value. |
Creates an array of strings that is passed by value. |
|
As an array of structures that contain strings by value. |
Creates an array of structures that contain strings and the array is passed by value. |