Actually, it is possible to use a std::string with Windows API calls. But you have to
resize them rather
reserve them (
see notes below for caveats!)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#define USING_WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
std::string path(MAX_PATH, '\0'); // fill with null chars
GetModuleFileName(NULL, &path[0], path.length());
cout << "module path (before resize) = \"" << path << "\n" << endl;
// this is needed to adjust the size to what it actually is,
// so operator<<, etc. behave correctly (the string works
// with what it knows the length to be, not the null term.)
path.resize(strlen(&path[0]));
cout << "module path = \"" << path << "\n" << endl;
return 0;
}
|
module path (before resize) = "c:\test\test.exe
"
module path = "c\test\test.exe" |
Note that:
- using std::strings like this is
offically sanctioned (i.e. part of the standard) in C++11, as std::string's storage is now mandated to be contiguous, but not in C++03.
- while not previously part of the standard, all major implementations of std::string already use contiguous storage due to other requirements of the standard, so it was already a
de facto standard (which C++11 picked up). See Herb Sutter's comments on this (link below.)
(It's certainly safe to use this previously
non-standard approach with the std::string that ships with Visual C++. And if you're using C++11, it's totally fair game!)
-
but usually, the C++ standard container of choice in this circumstance is std::vector<char>, as std::vector's storage has always been guaranteed to be contiguous, allowing you to safely use, e.g.
1 2 3 4 5 6 7 8 9
|
// The preferred way
std::vector<char> buf(fileSize);
// etc
ReadFile(hFileIn, &buf[o], buf.size(), &BytesRead, FALSE);
// etc
|
.
Andy
PS See Herb Sutter's response to the question “What is with std::string?” on this page:
Cringe not: Vectors are guaranteed to be contiguous
http://herbsutter.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/