SafeHandle.SetHandleとは? わかりやすく解説

SafeHandle.SetHandle メソッド

メモ : このメソッドは、.NET Framework version 2.0 で新しく追加されたものです。

ハンドルを指定した既存のハンドルに設定します。

名前空間: System.Runtime.InteropServices
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Protected Sub SetHandle ( _
    handle As IntPtr _
)
Dim handle As IntPtr

Me.SetHandle(handle)
protected void SetHandle (
    IntPtr handle
)
protected:
void SetHandle (
    IntPtr handle
)
protected void SetHandle (
    IntPtr handle
)
protected function SetHandle (
    handle : IntPtr
)

パラメータ

handle

使用する既存のハンドル。

解説解説
使用例使用例

SetHandle メソッドを実装する方法の例を次に示します。ハンドルを指定した既存のハンドルに確実に設定するには、ネイティブ ハンドルの割り当てと SafeHandle オブジェクト内でのそのハンドルの以降の記録を必ず分離不可能な状態にすることが必要です。これらの操作間でエラーが発生すると (スレッドの中止やメモリ不足の例外によるエラーなど)、ネイティブ ハンドルがリークされることになります。このコード例では、制約された実行領域を使用して信頼性を実現する方法を示しています。

<StructLayout(LayoutKind.Sequential)> _
Structure MyStruct
    Public m_outputHandle As IntPtr
End Structure 'MyStruct


NotInheritable Class MySafeHandle
    Inherits SafeHandle

    ' Called by P/Invoke when returning SafeHandles
    Public Sub New()
        MyBase.New(IntPtr.Zero, True)

    End Sub


    Public Function AllocateHandle() As
 MySafeHandle
        ' Allocate SafeHandle first to avoid failure later.
        Dim sh As New MySafeHandle()

        RuntimeHelpers.PrepareConstrainedRegions()
        Try
        Finally
            Dim myStruct As New
 MyStruct()
            NativeAllocateHandle(myStruct)
            sh.SetHandle(myStruct.m_outputHandle)
        End Try

        Return sh

    End Function


[StructLayout(LayoutKind.Sequential)]
struct MyStruct
{
    public IntPtr m_outputHandle;
}

sealed class MySafeHandle : SafeHandle
{
    // Called by P/Invoke when returning SafeHandles
    public MySafeHandle()
        : base(IntPtr.Zero, true)
    {
    }

    public MySafeHandle AllocateHandle()
    {
        // Allocate SafeHandle first to avoid failure later.
        MySafeHandle sh = new MySafeHandle();

        RuntimeHelpers.PrepareConstrainedRegions();
        try { }
        finally
        {
            MyStruct myStruct = new MyStruct();
            NativeAllocateHandle(ref myStruct);
            sh.SetHandle(myStruct.m_outputHandle);
        }

        return sh;
    }

.NET Framework のセキュリティ.NET Framework のセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
SafeHandle クラス
SafeHandle メンバ
System.Runtime.InteropServices 名前空間

SafeHandle.SetHandle メソッド




英和和英テキスト翻訳

英語⇒日本語日本語⇒英語

辞書ショートカット

すべての辞書の索引

SafeHandle.SetHandleのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



SafeHandle.SetHandleのページの著作権

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.

©2026 GRAS Group, Inc.RSS