【发布时间】:2011-04-03 12:20:24
【问题描述】:
我用 FileStream 在 C# 中打开一个文件,并通过这一行得到文件句柄号:
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.
谢谢。
【问题讨论】:
-
您确定要这样做吗?即使可以做到,只是传递文件名可能会更简单......
-
我的第一个问题是“为什么?”。这可能是可行的,但它会很丑陋。我宁愿退后一步,分析需要什么最终结果,看看是否有更清洁的方法。