Basic types to expose on a C++ API

I'm targeting Windows but I don't see any reason why some API code I'm writing cannot use basic C++ types. What I want to do is expose methods that return strings and ints. In the C# world I'd just use string, and have a unicode string, but in VC++ I've got the option of using std::string, std::wstring, or MFC/ATL CStrings.

Should I just use std::wstring exclusively to support unicode, or can I use std::string which would be compiled to unicode based on my build settings? I'm leaning toward the latter. I'd prefer to provide Get[Item]AsCString() methods on my objects for other string types.

Also should I be using size_t instead of integer?

The API is going to be used by me, and perhaps a future developer working on the C++ GUI. It is a way to separate concerns. My preferences:

  • Intuitiveness for other developers.
  • Forward compatibility with VC++
  • Compatibility with other C++ compilers
  • Performance (this is a lesser concern for me, but need the startup time for rest of my app)
  • Any guides would be appreciated.


    You should probably stick to the STL string type. The MFC CString class is built on top of that nowadays anyway.

    As has been noted before, using wstring is not a magic bullet to address Unicode issues since there are many Unicode characters that still require multiple wchars to encode.

    Using Utf-8 instead has potential benefits (you don't have to worry about endianness for example).

    On Windows, all modern kernels are wchar based, so there is a (minimal) performance overhead involved if you use the 8bit char versions of APIs.


    In your situation it would take me few hours / days to develop an opinion and decide. First of all, I very much prefer C_API to C++_API, even for C++ code. Then the answer would be char*, or wchar*, or TCHAR*. Now, try to guess if you REALLY expect the need for UNICODE. Great majority of my projects (including those with GUIs), had no need for UNICODE, the simplicity and familiarity of plain C-arrays is often hard to beat.

    In short, try to predict what will be your needs, do not try to look too far into future (2 years is a good mark), then come up with the simplest solution to meet the needs.

    Last: To answer your question more directly, I would start with std::string as my 1st choice to evaluate. Unless I would find some bid advantage in favor of the other choices, I would stay with it.


    Using std::wstring/string instead of the MFC CString will allow you to port your code to other frameworks (eg Qt for Windows).

    Even when using std::string you could encode the strings in UTF-8, so your API will still be able to return UNICODE strings. Keep in mind that even wstring is really UTF-16 and not the full 32 bits UNICODE (while on some operating systems wstring is UTF-32).

    链接地址: http://www.djcxy.com/p/51200.html

    上一篇: Intellij IDEA X:任何多核设置需要调整?

    下一篇: 在C ++ API上公开的基本类型