Should I use std :: string or Windows data types with DirectX?

I am currently working on a project based on DirectX, and I'm struggling with something. Although the DirectX SDK is heavily dependent on Windows data types, such as LPSTR , LPCSTR , ... I used std::string for my own classes, which were easy to work with, but it is strange to mix both ways of handling strings. Although this is a vague question, what do you suggest - should I work with string or with Windows pointers for different types of strings in order to maintain some consistency?

+4
source share
3 answers

LPSTR is just an alias for char* , and LCPSTR is an alias for const char* , so your question actually sounds like this: "Should I use C ++ strings or C strings?"

Well, C ++ std::string has a member function called c_str() (or an equivalent data() function for STL compatibility) that returns a (non-modifiable) C string. Therefore, anytime the function accepts LPCTSTR , you can provide the output of c_str() as an argument.

I suggest you work with C ++ std::string whenever possible, safer.

+5
source

In modern C ++ code, I would simply use a reliable string class like std::string , or better std::wstring to support Unicode UTF-16 with Windows. You can then convert to raw C strings at the borders of the API.

To get the read-only raw C string pointer, you can use the std::[w]string::c_str() .

Instead, if you want to change the std::[w]string buffer, you can first call the .resize() method to prepare the string buffer, which makes it large enough; then you can use &str[0] to access the internal buffer for these APIs than you need to write to it.

Note that in specific Windows ATL code, CString is another convenient string class that you might want to use. It has some platform-friendly tools, such as loading a string from resources (which is good for localizing applications).

Since CString offers implicit conversion to LPCTSTR , you can simply pass CString instances to APIs that expect raw LPCTSTR . Instead, if you need to modify the internal CString buffer, you can use the GetBuffer() / ReleaseBuffer() methods.

+2
source

Based on @Andy Prowl's answer, you can program everything using the β€œT” lines (ie LPTSTR instead of LPSTR or LPWSTR ). The exact type T (really TCHAR ) is set at compile time, depending on whether you have UNICODE and _UNICODE #defined . This gives you compatibility with both.

You can still use C ++ strings using this technique by deriving the tstring class from basic_string<> :

 typedef std::basic_string<TCHAR> tstring; 
+1
source

All Articles