writing directly to std::string internal buffers

前端 未结 9 1129
猫巷女王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:58

    You can use char buffer allocated in unique_ptr instead vector:

    // allocate buffer
    auto buf = std::make_unique(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 
    #include 
    #include 
    
    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.

提交回复
热议问题