给定一个QFileDevice实例(一个QFileQSaveFile)-如何获得该文件的 native Windows HANDLE?并且此句柄可以与ReOpenFile一起使用吗?

最佳答案

QFileDevice::handle() 返回从 fd 获得的C文件描述符(QFSFileEnginePrivate::nativeHandle-一个小整数)。该文件描述符就是从 _open_osfhandle 获得的文件描述符。您需要使用 _get_osfhandle 返回HANDLE

struct FdHandle {
  int fd = -1;
  HANDLE handle = INVALID_HANDLE_VALUE;
  operator HANDLE() const { return handle; }
  bool isFdValid() const { return fd != -1; }
  bool isHandleValid() const { return handle != INVALID_HANDLE_VALUE; }
};

FdHandle windowsHandleOf(QFileDevice* dev) {
  auto fd = dev->handle();
  return {fd, (HANDLE)_get_osfhandle(fd)};
}

ReOpenFile 可能返回不同的文件句柄,因此您可能需要为其重新打开文件。重载的ReOpenFile处理它:
struct ReOpenResult {
  enum { OK = 0, FileClosed = 10, NoHandle = 20,
         OldHandle = 30, OpenFailed = 40 } rc;
  HANDLE handle = INVALID_HANDLE_VALUE;
  operator HANDLE() const { return handle; }
  explicit operator bool() const { return rc == OK; }
  bool isHandleValid() const { return handle != INVALID_HANDLE_VALUE; }
};

ReOpenResult ReOpenFile(QFile *file, DWORD access, DWORD shareMode, DWORD flags) {
  if (!file->isOpen())
    return {ReOpenResult::FileClosed};
  auto oldHandle = windowsHandleOf(file);
  if (oldHandle == INVALID_HANDLE_VALUE)
    return {ReOpenResult::NoHandle};
  auto newHandle = ReOpenFile(oldHandle, access, shareMode, flags);
  if (newHandle == INVALID_HANDLE_VALUE)
    return {ReOpenResult::OldHandle, oldHandle};
  if (!open(file, file->openMode(), newHandle))
    return {ReOpenResult::OpenFailed, oldHandle};
  return {ReOpenResult::OK, newHandle};
}

需要open的“缺失” HANDLE是:
struct OpenResult {
  enum { OK = 0, SameHandleOK = 1, InvalidHandle = 10, CCloseFailed = 20,
         InvalidFd = 30, OpenFailed = 40 } rc = OK;
  explicit operator bool() const { return rc < InvalidHandle; };
};

OpenResult open(QFile* file, QIODevice::OpenMode mode, HANDLE handle) {
  if (handle == INVALID_HANDLE_VALUE)
    return {OpenResult::InvalidHandle};
  if (file->isOpen() && windowsHandleOf(file) == handle)
    return {OpenResult::SameHandleOK};
  file->close();
  if (auto fd = file->handle() != -1)
    if (_close(fd)) // the C handle is still open, don't leak it
      return {OpenResult::CCloseFailed};
  int flags = 0;
  if (mode & QIODevice::Append)
    flags |= _O_APPEND;
  if (!(mode & QIODevice::WriteOnly))
    flags |= _O_RDONLY;
  auto fd = _open_osfhandle((intptr_t)handle, flags);
  if (fd == -1)
    return {OpenResult::InvalidFd};
  if (!file->open(fd, mode, QFileDevice::AutoCloseHandle))
    return {OpenResult::OpenFailed};
  return {};
}

关于windows - 如何从QFile或QSaveFile获取Windows Handle以获取ReOpenFile?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50191480/

10-09 20:23