直接写入std :: string内部缓冲区 [英] writing directly to std::string internal buffers

查看:285
本文介绍了直接写入std :: string内部缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种方法来将一些数据填充到跨越DLL边界的字符串中。因为我们使用不同的编译器,所有我们的dll接口都是简单的char *。

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*.

有一个正确的方法传递一个指针到dll函数,字符串缓冲区直接?

Is there a correct way to pass a pointer into the dll function such that it is able to fill the string buffer directly?

string stringToFillIn(100, '\0');
FunctionInDLL( stringToFillIn.c_str(), stringToFillIn.size() );   // definitely WRONG!
FunctionInDLL( const_cast<char*>(stringToFillIn.data()), stringToFillIn.size() );    // WRONG?
FunctionInDLL( &stringToFillIn[0], stringToFillIn.size() );       // WRONG?
stringToFillIn.resize( strlen( stringToFillIn.c_str() ) );

看起来最有前景的是& stringToFillIn [0],但这是一个正确的方法这,因为你会认为string :: data()==& string [0]?似乎不一致。

The one that looks most promising is &stringToFillIn[0] but is that a correct way to do this, given that you'd think that string::data() == &string[0]? It seems inconsistent.

或者最好是吞下一个额外的分配,避免这个问题:

Or is it better to swallow an extra allocation and avoid the question:

vector<char> vectorToFillIn(100);
FunctionInDLL( &vectorToFillIn[0], vectorToFillIn.size() );
string dllGaveUs( &vectorToFillIn[0] );


推荐答案

我不确定标准是否保证数据在 std :: string 中存储为 char * 。我可以想到的最便携的方法是使用 std :: vector ,它保证将其数据存储在连续的内存块中:

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.

这篇关于直接写入std :: string内部缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆