How to open a file when the file descriptor number is known?

I open a file in C # with FileStream, and I got the file descriptor number with this line:

IntPtr file_handle = fs.SafeFileHandle.DangerousGetHandle();

Now I want to pass this handle to C ++ code and use this handle value to access the file. Is it possible? How to open a file with just a file descriptor in C ++?

Thank.

Update

I am using C # for P / Invoke in a C ++ Win32 DLL (not a COM-DLL). I open the file in C # as a FileStream and pass the handle to C ++. Here are some of my code in the 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;
}

And here is my C # code:

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

But I get this error:

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

Thank.

0
source share
3 answers

You can use win32 calls, just like the filestream / file constructors do (via 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

, , , , :

++

, . . , :

[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

+2

- . , # ++ - , marshall IntPtr HANDLE.

, - .

, , , :

  • ++
  • , ++, .
+1

++ - ++/CLI, . FileStream ++.

If C ++ is native code, you can use the file descriptor wherever you usually use the Windows value HANDLEfor files such as ReadFileand WriteFile. You would not use a handle to open the file because it is already open. If you need another copy of the descriptor or if you want to pass the descriptor to another process, use DuplicateHandle. If you need a value with POSIX-like functions such as _readand _writethen call _open_osfhandleto get the file descriptor, you can wrap the file descriptor in stream C FILE*with _fdopen.

0
source

Source: https://habr.com/ru/post/1791273/


All Articles