我有一个 Visual Studio 2008 C# .NET 3.5 应用程序,它 P/Invokes 一个接受文件句柄作为参数的本机方法。最初,我只是使用 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);
}
谢谢,保罗