James Fielder
James Fielder

Reputation: 133

Using rapidjson and ATL CString

I am attempting to use the rapidjson library with Microsoft ATL CString type, as shown in the example below.

#include "stdafx.h"
#include "rapidjson\document.h"

using namespace rapidjson;
typedef GenericDocument<UTF16<> > WDocument;

int main()
{
    WDocument document;
    CString hello = _T("Hello");
    document.SetObject();
    document.AddMember(_T("Hello"), hello, document.GetAllocator());
    return 0;
}

This fails with the compiler error

'rapidjson::GenericValue::GenericValue(rapidjson::GenericValue &&)': cannot convert argument 1 from 'CString' to 'rapidjson::Type' rapidjson document.h 1020

which does imply that a conversion between CString and a format which rapidjson would need is required. I know that rapidjson internally uses wchar_t as the encoding for the UTF16 version of its functions, however I am not sure how to convert a CString to a wchar_t (or array of wchar_t) in a way that rapidjson will be able to use the string as it uses strings defined by the _T macro.

I have looked at the msdn resources on converting between string types here but this only gives a way to return a pointer to the first member of an array of wchar_t, which rapidjson cannot then use.

Upvotes: 1

Views: 1647

Answers (1)

James Fielder
James Fielder

Reputation: 133

The correct way to do this is to use one of the constructors rapidjson provides for its GenericValue class, namely the constructor for a pointer to a character encoding type and a character length.

GenericValue(const Ch* s, SizeType length) RAPIDJSON_NOEXCEPT : data_(), flags_() { SetStringRaw(StringRef(s, length)); }

This constructor can take a pointer to any of the character types which rapidjson accepts along with a length and then read this into a value. For the ATL::CString class, this can be accomplished with the .GetString() and .GetLength() methods available on a CString object. A function to return a Value which can be used in a DOM tree would look like this:

typedef GenericValue<UTF16<> > WValue;

WValue CStringToRapidjsonValue(CString in)
{
    WValue out(in.GetString(), in.GetLength());
    return out;
}

Upvotes: 2

Related Questions