writing directly to std::string internal buffers

前端 未结 9 1114
猫巷女王i
猫巷女王i 2020-11-29 07:22

I was looking for a way to stuff some data into a string across a DLL boundary. Because we use different compilers, all our dll interfaces are simple char*.

Is ther

相关标签:
9条回答
  • 2020-11-29 07:45

    I'd not construct a std::string and ship a pointer to the internal buffers across dll boundaries. Instead I would use either a simple char buffer (statically or dynamically allocated). After the call to the dll returns, I'd let a std::string take over the result. It just feels intuitively wrong to let callees write in an internal class buffer.

    0 讨论(0)
  • 2020-11-29 07:50

    I'm not sure the standard guarantees that the data in a std::string is stored as a char*. The most portable way I can think of is to use a std::vector, which is guaranteed to store its data in a continuous chunk of memory:

    std::vector<char> buffer(100);
    FunctionInDLL(&buffer[0], buffer.size());
    std::string stringToFillIn(&buffer[0]);
    

    This will of course require the data to be copied twice, which is a bit inefficient.

    0 讨论(0)
  • 2020-11-29 07:58

    You can use char buffer allocated in unique_ptr instead vector:

    // allocate buffer
    auto buf = std::make_unique<char[]>(len);
    // read data
    FunctionInDLL(buf.get(), len);
    // initialize string
    std::string res { buf.get() };
    

    You cannot write directly into string buffer using mentioned ways such as &str[0] and str.data():

    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main()
    {
        std::string str;
        std::stringstream ss;
        ss << "test string";
        ss.write(&str[0], 4);       // doesn't working
        ss.write(str.data(), 4);    // doesn't working
        std::cout << str << '\n';
    }
    

    Live example.

    0 讨论(0)
提交回复
热议问题