我如何将std :: filesystem :: path转换为LPCSTR以用于LoadLibrary()变量之一?

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

[在Windows上,我试图使用LoadLibrary()的一种变体来打开以前用dll写入std::filesystem::pathofstream

注意:我知道dll的编写正确,因为我可以通过在运行时链接到它来以标准方式使用它。

我一直试图结合下面两个答案中的方法。

How to convert std::string to LPCSTR?

how to convert filesystem path to string

[这似乎应该是非常基本的,但是到目前为止,我尝试过的任何操作都导致我无法转换为LPCSTR或出现类似C2228: left of '.c_str' must have class/struct/union之类的错误,而对此我感到困惑。

这是一个简单的示例:

// Assuming I have 
// std::filesystem::path path1 
// correctly set, I should be able to directly access it in
// a number of ways; i.e. path1.c_str(), path1.string.c_str(), etc.
// in order to pass it the function or a temp variable.
// However direct use of it in LoadLibrary() fails with the C2228 error.

HINSTANCE hGetProcIDDLL = LoadLibrary(path1.c_str());

我尝试避免使用该宏,并且没有运气直接调用LoadLibraryA()。我还尝试了各种方法来通过path1path1.string(),path1.wstring()等传递path1.string.c_str(),但是没有运气。我还尝试了多种方式使用temp变量,以避免在LoadLibrary()中进行强制转换。

LPCSTR temp_lpcstr = path1.c_str();  // Also tried things like path1.string() path1.string.c_str()

// Also tried just using a temp string...
std::string temp_string = path1.string(); // and variants.

我愿意尝试使用编码(例如path1.u8string()等),但是我认为直接使用LoadLibraryA()并不需要。

我正在尝试避免使用C强制转换,并且更喜欢使用c ++ static_或dynamic_,但我将使用任何可行的方法。

感谢您的任何帮助。

提前感谢。

UPDATE

@@ eryk-sun的评论和@Gulrak的回答为我解决了。看起来像我的设置一样,path1.c_str()单独是wchar_t,但是LoadLibrary()宏没有将其拾取并将其直接定向到LoadLibraryW()。

注意:对于将来可能会偶然发现此问题的任何人,这里是我特定设置的更多详细信息。我正在使用从16.1.0(〜VS2019)开始的MSVC编译器,但是这是从VSCode和CMake调用的。我没有明确定义_UNICODE,但是VSCode的intellisense肯定认为它已在某处定义,并将我指向LoadLibraryA()。但是,我认为编译器实际上并未看到该定义,因此它将path1.c_str()解释为wchar_t

c++ windows loadlibrary std-filesystem
2个回答
1
投票

实际上,在Windows上您应该能够使用LoadLibraryW(path1.c_str()),因为在Windows上,返回的std :: filesystem :: path :: c_str()的类型应该为const wchar_t*,因此非常适合预期的LoadLibraryW LPCWSTR

我的猜测是C2228的错误,您尝试根据注释给出的path1.string.c_str(),应该是path1.string().c_str()。这将为您提供LPCSTRLoadLibaryA兼容字符串,但是如果您的路径中有非ASCII的机会,我建议您使用显式的LoadLibaryW版本。

[以任何方式:当将WinAPI与std::filesystem::path接口时,应使用显式的A / W版本以使代码安全,而与_UNICODE的状态无关,我始终建议使用*W版本。


1
投票

您应该使用string类的path成员函数,该函数返回std::string。然后在返回的字符串上调用c_strstd::filesystem::path path /* = initialization here */; std::string str = path.string(); /* some handle = */ LoadLibrary(str.c_str());

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