ファイル ハンドルをパラメーターとして受け入れるネイティブ メソッドを P/Invokes する Visual Studio 2008 C# .NET 3.5 アプリケーションがあります。もともと、私は FileStream.SafeFileHandle.DangerousGetHandle() を使用してファイル ハンドルを取得していました。しかし、FX COP をオンにした後、CA2001 に関する警告が表示されました。それで、少し調べたところ、「制約付き実行領域」を発見しました。これは私にとって新しいことであり、それに関する多くの情報を見たことがありません。私は、より経験豊富な誰かが見て、これを正しく行ったことを確認できることを望んでいました.
class MyClass
{
public static bool Write(string filename)
{
using (var fs = new System.IO.FileStream(filename,
System.IO.FileMode.Create,
System.IO.FileAccess.Write,
System.IO.FileShare.None))
{
bool got_handle;
bool result;
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
fs.SafeFileHandle.DangerousAddRef(ref got_handle);
result = NativeMethods.Foo(fs.SafeFileHandle.DangerousGetHandle());
if (got_handle)
fs.SafeFileHandle.DangerousRelease();
}
return result;
}
}
}
internal sealed class NativeMethods
{
[DllImport("mylib.dll",
EntryPoint = "Foo",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode,
ExactSpelling = true,
SetLastError = true)]
public static extern bool Foo(IntPtr hFile);
}
ありがとう、ポールH