Sign in with Microsoft
Sign in or create an account.
Hello,
Select a different account.
You have multiple accounts
Choose the account you want to sign in with.

狀況

當動態目標 Microsoft.NET Framework 4.5.1 或 Microsoft.NET Framework 4.5.2 和程式碼的程式碼繫結至方法 (例如,使用 Windows PowerShell、 IronPython、 IronRuby 或另一種動態語言的指令碼) 呼叫System.Runtime.InteropServices.Marshal.SizeOf方法或System.Runtime.InteropServices.Marshal.PtrToStructure方法時,您可能會遇到下列問題。

注意已編譯成受管理的可執行檔的程式碼並不會呈現這些問題,除非該程式碼在 C# 中使用動態的關鍵字。

問題 1

呼叫System.Runtime.InteropServices.Marshal.SizeOf擲回下列的MethodInvocationException例外狀況︰

型別 ' <型別名稱>' 無法封送處理為 unmanaged 的結構;可以計算任何有意義的大小或位移。

問題 2

呼叫System.Runtime.InteropServices.Marshal.PtrToStructure擲回下列的MethodInvocationException例外狀況︰

指定的結構必須 blittable 或有配置資訊。


問題 3

呼叫System.Runtime.InteropServices.Marshal.PtrToStructure擲回下列的RuntimeBinderException例外狀況︰

不能隱含轉換 'void' 到 'object' 型別。


原因

之所以發生這個問題,是因為指令碼引擎和動態語言可能會將繫結至.NET Framework 中引入新多載。特別是,先前使用Marshal.SizeOf(Type)的呼叫可能現在呼叫Marshal.SizeOf < T > (T),而且使用Marshal.PtrToStructure (IntPtr,型別)的呼叫可能現在呼叫Marshal.PtrToStructure < T >(IntPtr, T)。這項變更將導致方法或執行階段繫結器擲回例外狀況。

因應措施

若要解決這個問題,請變更程式碼,使其使用正確的多載,如果您的語言,可讓您執行這項操作。如果您無法指定特定的方法多載,變更程式碼,使它改用新的方法多載正確。

C# 動態引動過程

在呼叫方法SizeOf或方法PtrToStructure內新增設計成用 System.Type轉型。例如︰

object obj = System.Runtime.InteropServices.Marshal.PtrToStructure(ptr, (System.Type)type);int size = System.Runtime.InteropServices.Marshal.SizeOf((System.Type)type);


注意這需要時才是動態的其中一個方法的引數。

Windows PowerShell 指令碼

在呼叫方法SizeOf或方法PtrToStructure內新增設計成用 System.Type轉型。例如︰

$size = [System.Runtime.InteropServices.Marshal]::SizeOf([System.Type] $type)
$obj = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [System.Type] $type)

IronPython 指令碼

建立型別的新型別執行個體,然後使用新的方法多載。例如︰

typeInstance = type()
size = System.Runtime.InteropServices.Marshal.SizeOf(typeInstance)

obj = System.Runtime.InteropServices.Marshal.PtrToStructure(ptr, typeInstance)

狀態

Microsoft 已確認這是<套用>一節所列出的 Microsoft 產品的問題。

參考

Need more help?

Want more options?

探索訂閱權益、瀏覽訓練課程、瞭解如何保護您的裝置等等。

社群可協助您詢問並回答問題、提供意見反應,以及聆聽來自具有豐富知識的專家意見。

Was this information helpful?

How satisfied are you with the translation quality?
What affected your experience?
By pressing submit, your feedback will be used to improve Microsoft products and services. Your IT admin will be able to collect this data. Privacy Statement.

Thank you for your feedback!

×