-
cstring and apis
I used to use the c-style method of working with strings and such, but always had a hard time. So I started using the cstring header and using the string class. It's alot easier with the overloaded operators and such. However, I use Win32 API to do all my work mostly, and most of the API functions take in (const char*) or similar. When replacing what I had in the functions with strings, I ended up using (LPSTR)var.c_str() to make the code compile. Well, as expected, it compiled, but also expected, the program crashes because of it. Is there a technique or method with using strings in the Win32 API? Other APIs (Winsock, OpenGL, etc)? Thanks for any information.
-
If your API works with const char*, then you can use var.c_str() without the explicit cast to LPSTR. Also, I believe it should work wherever the API looks for an LPCSTR (LPCTSTR should be fine also).
However, LPSTR is different, since it is missing the 'C' that stands for const. You cannot and should not cast a string or a const char* to an LPSTR. That removes the const, which is there for a reason. If you need an LPSTR or a char*, then you simply need to make a local c-style string variable and copy the string's value to it before passing that variable to the function and possibly updating the string afterwards if the value changed. For example:
Code:
std::string var = "My String";
// ...
char tmp[100];
strcpy(tmp, var.c_str());
Win32APIFunc(tmp);
var = tmp;
Of course, you have to be careful that the size you choose is big enough for the string, but I think many Win32 API functions specify the maximum length of the string they will modify. Remember, you should only do this if the function calls for a char* or LPSTR, not for a const char* or LPCSTR.
-
Don't use the raw char array, a vector is usually easier:
Code:
std::string str("I want to pass this");
std::vector<char> vec(str.size()+1)
vec.assign(str.begin(), str.end());
vec.push_back(0);
legacy_api(&vec[0]);
Don't worry about too small buffers, don't worry about deallocation.
And if the function doesn't require \0termination, it's even easier.
Code:
std::string str("I want to pass this");
std::vector<char> vec(str.begin(), str.end())
legacy_api(&vec[0], vec.size());