5

When should we use this attribute and why do we need it? For example, if the native function in c takes as a parameter a pointer to unsigned char, and I know that it's needed to fulfill the array of unsigned chars, why can't I use array of bytes in C# to use this function? Is it necessary to do marshalling?

4

3 に答える 3

6

ほとんどの場合、ランタイムはネイティブ コードとマネージド コードの間でデータをマーシャリングする方法を自動的に決定できるため、通常は属性を指定する必要はありません。MarshalAs定義にあいまいさがある場合 (およびデータをマーシャリングする方法をランタイムに正確に伝えたい場合)、またはデフォルト以外の動作が必要な場合にのみ必要です。

私の経験でMarshalAsは、ネイティブコードには非常に多くの異なる表現があるため、文字列を操作する場合にのみ必要です。unicode/ansi、c-strings かどうかなど。

于 2011-06-16T03:51:24.397 に答える
1

MarshalAs 属性の追加の使用は、ByValArray および SizeConst パラメーターを使用して、固定サイズの配列 (固定サイズの文字列を含む) をマーシャリングすることです。たとえば、Windows API の多くの構造には、固定サイズの文字列が含まれています。

于 2011-06-16T05:28:33.443 に答える