我有一个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);
}
Run Code Online (Sandbox Code Playgroud)
谢谢,PaulH