C++ 如何将字符串附加到 BYTE 数组

C++ How to append a string to BYTE array?

本文关键字:BYTE 数组 字符串 C++      更新时间:2023-10-16

我在C++中有以下代码(用Visual Studio 2010编写(。

void TEST(BYTE  data[], int size)
{
    wstring aData = L"Here is my string";
    //something code to append aData string to data array
    WinHttpClient client(url);
    // Send HTTP post request.
    client.SendHttpRequest(L"POST");
}

如何将数据字符串附加到数据字节数组。

简短的回答:你不能。

所以你得到了 BYTE[] 和大小,但你不知道数据是在堆栈上还是堆上,所以你不能只用realloc或其他东西来让它变大。

一种方法是确保数组大于所需大小,并传递当前和最大大小。

另一种方法是更改 API 以允许您使用 realloc 或类似来调整数组大小。

我能想到的唯一不更改 API 的方法是在 data 中使用某种标记来分隔已用和未使用的空间(不适用于二进制数据(。 例如,0 表示未使用,因此您可以查找第一个0并从那里开始追加。

编辑也许我误读了意图。如果您不想进行永久更改,则可以获取本地副本,附加到该副本(并确保将其清理干净(。我以为你想要一个永久的"就地"附加。

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <boost/locale/encoding_utf.hpp>
std::wstring utf8_to_wstring(const std::string& str)
{
    return utf_to_utf<wchar_t>(str.c_str(), str.c_str() + str.size());
}
int main()
{
    unsigned char test[10];
    std::string tesStr((char*)test);
    wstring temp = utf8_to_wstring(tesStr);
}