我在 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/