c# - 已知文件句柄号时如何打开文件?

标签 c# c++ interop

我在 C# 中使用 FileStream 打开一个文件,并通过以下行获得了文件句柄号:

IntPtr file_handle = fs.SafeFileHandle.DangerousGetHandle();

现在我想将这个句柄传递给 C++ 代码,并使用这个句柄值来访问文件。这可能吗?如何在 C++ 中打开只有文件句柄的文件?

谢谢。

更新

我使用 C# P/Invoke 到 C++ Win32 DLL(不是 COM DLL)。我在 C# 中将文件作为 FileStream 打开,并将句柄传递给 C++。这是我在 C++ DLL 中的一些代码:

extern "C" __declspec(dllexport)void read_file(HANDLE file_handle)
{
    char buffer[64];
    ::printf("\nfile = %d\n",file_handle);

    if(::ReadFile(file_handle,buffer,32,NULL,NULL))
    {
        for(int i=0;i<32;i++)
            cout<<buffer[i]<<endl;
    }
    else
        cout<<"error"<<endl;
}

这是我的 C# 代码:

    [DllImport("...",EntryPoint = "read_file", CharSet = CharSet.Auto)]
    public static extern void read_file(IntPtr file_handle_arg);

但是我得到这个错误:

Unhandled Exception: System.AccessViolationException: Attempted to read or write
 protected memory. This is often an indication that other memory is corrupt.

谢谢。

最佳答案

您可以使用 win32 调用,就像文件流/文件构造函数一样(通过 p/invoke)。

.NET Reflector 中破解它,看起来它正在使用这个函数:

[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private static extern SafeFileHandle CreateFile(
  string lpFileName,
  int dwDesiredAccess,
  FileShare dwShareMode,
  SECURITY_ATTRIBUTES securityAttrs,
  FileMode dwCreationDisposition,
  int dwFlagsAndAttributes,
  IntPtr hTemplateFile);

这是一个官方引用:

http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx

不过,这只是为了打开文件,正如您所说的那样:

How to open a file with merely a file handle in C++

如果你想读取一个已经打开的文件,你可能会遇到更多的麻烦。我不知道。您也许可以使用此功能:

[DllImport("kernel32.dll", SetLastError=true)]
internal static extern unsafe int ReadFile(
  SafeFileHandle handle,
  byte* bytes,
  int numBytesToRead,
  IntPtr numBytesRead_mustBeZero,
  NativeOverlapped* overlapped
);

http://msdn.microsoft.com/en-us/library/aa365467(v=VS.85).aspx

关于c# - 已知文件句柄号时如何打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3562513/

相关文章:

c# - 将数组转换为数组数组的数组

scala - 如何传递 Scala UserDefinedFunction 其中输出是复杂类型(使用 StructType 和 StructField)以从 Pyspark 使用

C#:从非事件窗口发送输入

c# - Windows Phone 8 上的 RestSharp 没有响应

c# - 抽象类实例化

c# - 偷看后从并发队列中删除元素的模式

c++ - 在 C++ 中执行 unix 命令

c++ - xcb 鼠标移动导致输入滞后

c++ - TProcess - 从多个 Process.Input.Write(...) 命令捕获输出

javascript - 如何通过 Dart 互操作此 Javascript?