Q:

Error in c++ call between exe and dll

I'm very lost with this c++ error. 
I have one "exe" that it exports ".lib", and load a "dll" that imports this ".lib". I can use this methods whituout problem. But when i use "EscapeJson", exception appears. if i copy the code into the library and replace "CoreHelper::EscapeJson" with "EscapeJson" (same library) all is Ok ... 
what's wrong?
My.EXE (Export) -> My.lib (Import) -> MyDll.dll
   ^                                      |
   `---------------------------------------

Also the code works, because the "EscapeJson" returns the value successfully...

Escape Json Source
std::string CoreHelper::EscapeJson(char * input, int length)
{
    std::ostringstream o;
    for (int x = 0; x < length; x++)
    {
        char c = input[x];
        switch (c)
        {
        case '"': o << "\\\""; break;
        case '\\': o << "\\\\"; break;
        case '\b': o << "\\b"; break;
        case '\f': o << "\\f"; break;
        case '\n': o << "\\n"; break;
        case '\r': o << "\\r"; break;
        case '\t': o << "\\t"; break;
        default:
            if ('\x00' <= c && c <= '\x1f')
            {
                o << "\\u"
                    << std::hex << std::setw(4) << std::setfill('0') << (int)c;
            }
            else
            {
                o << c;
            }
        }
    }
    return o.str();
}

A:

You can't pass a std::string (or just about any other non-POD type) across DLL boundaries.  In this case, the original memory of the std::string is allocated inside of the EXE and is managed by the memory manager compiled into the EXE.  The DLL will not be able to free it correctly, only the EXE can.
You need to use interop-safe data types and memory management techniques that are safe to use across DLL boundaries.
In this case, try something more like this instead:
char* CoreHelper::EscapeJson(char * input, int length)
{
    std::ostringstream o;
    //...
    std::string s = o.str();
    char *res = new char[s.size()+1];
    std::copy(s.begin(), s.end(), res);
    res[s.size()] = 0;
    return res;
}

void CoreHelper::FreeEscapedJson(char * input)
{
    delete [] input;
}

char *str = CoreHelper::EscapeJson(...);
// use str as needed...
CoreHelper::FreeEscapedJson(str);

