将 DLL 路径从 C++ 传递到 Fortran

问题描述 投票:0回答:1

我正在尝试将我所在的 DLL 的路径放入类型的局部变量中:

  char dbankpath[] = "c:\\temp";

由于我正在调用的 Fortran 函数的要求,我需要这种结束类型。

从这里的各种线程,我相信 DLL 路径可以通过以下方式在 DLLMain 中获得:

  wstring DLLPathAndName;
  wstring DLLPath;
  
  void setdllpath(wstring);
  
  BOOL APIENTRY DllMain( HMODULE hModule, 
                         DWORD   ul_reason_for_call, 
                         LPVOID  lpReserved )
    {
    switch (ul_reason_for_call)
      {
      case DLL_PROCESS_ATTACH:
      case DLL_THREAD_ATTACH:
      case DLL_THREAD_DETACH:
      case DLL_PROCESS_DETACH:
        break;
  
      const int BUFSIZE = 4096;
      wchar_t buffer[BUFSIZE];
  
      if (::GetModuleFileNameW(hModule, buffer, BUFSIZE - 1) <= 0) { return TRUE; }
  
      DLLPathAndName = buffer;
  
      size_t found = DLLPathAndName.find_last_of(L"/\\");
      DLLPath = DLLPathAndName.substr(0, found);
      setdllpath(DLLPath);
      break;
      }
  
    return TRUE;
    }

所以现在我在 wstring 中有了 DLL 路径。然后我将它传递到我的主代码中的另一个函数:

  std::wstring g_DLLPath[256];

  void setdllpath(std::wstring DLLPath) {
    g_DLLPath = DLLPath;
    }

将其复制到全局变量 g_DLLPath 中。

现在我需要将其放入 char dbankpath[],为此我编写了另一个函数(从此处的另一个线程获得):

  #include <cstdlib>
  
  void copywstringtochar(std::wstring wStr, char *buffer) {
  
    const wchar_t *input = wStr.c_str();
  
  // Count required buffer size (plus one for null-terminator).
    size_t size = (wcslen(input) + 1) * sizeof(wchar_t);
  
    #ifdef __STDC_LIB_EXT1__
        // wcstombs_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined
        size_t convertedSize;
        std::wcstombs_s(&convertedSize, buffer, size, input, size);
    #else
        std::wcstombs(buffer, input, size);
    #endif
  
    }

我打电话给:

   copywstringtochar(g_DLLPath,&commandfile);

但是这不会编译。我忍不住想我让这种方式太复杂了,在 Fortran 中它是 2 或 3 行代码。

有没有一种简单的方法可以将 DLL 路径放入 char dbankpath[]?

c++ dll
1个回答
0
投票

简单的做法是调用

GetModuleFileNameA
,将路径直接写入全局数组。有点像

GetModuleFileNameA(hModule, dbankpath, std::size(dbankpath))

with

dbankpath
声明了这样的事情

char dbankpath[_MAX_PATH];

如您所说,只需 2 或 3 行代码。

© www.soinside.com 2019 - 2024. All rights reserved.