如何return base64解码图像字节通过char类型的方法形式参数**

How to return base64 decoded image bytes through a methods formal parameter of type char**

作为 C++ 的新手,我仍在为指向指针的指针苦苦挣扎,我不确定我下面的方法是否正确 return 解码图像字节。

此方法从 API 获取 base64 编码的图像字符串。该方法必须遵循此签名,因为它是遗留代码的一部分,不允许缩写其最初编写的方式。所以签名必须保持不变。此外,为了简化代码,我在这里省略了异步调用和延续、异常等。

int __declspec(dllexport) GetInfoAndPicture(CString uid, char **image, long *imageSize)
{
    CString request = "";
    request.Format(url); 

    http_client httpClient(url);
    http_request msg(methods::POST);

    ...

    http_response httpResponse;
    httpResponse = httpClient.request(msg).get();  //blocking
    web::json::value jsonValue = httpResponse.extract_json().get();

    if (jsonValue.has_string_field(L"img"))
    {
        web::json::value base64EncodedImageValue = jsonValue.at(L"img");
        utility::string_t imageString = base64EncodedImageValue.as_string();  
        std::vector<unsigned char> imageBytes = utility::conversions::from_base64(imageString);
        image = (char**)&imageBytes;  //Is this the way to pass image bytes back? 
    *imageSize = imageBytes.size();
    }

    ...
}

调用者这样调用这个方法:

char mUid[64];
char* mImage;
long mImageSize;
...
resultCode = GetInfoAndPicture(mUid, &mImage, &mImageSize);

//process image given its data and its size

我知道指向指针的指针是什么,我的问题是针对这一行的

image = (char**)&imageBytes;

在给定上述方法签名和方法调用的情况下,通过 char** image 形式参数,这是 return 从 base64 解码的图像到调用代码中的正确方法吗?

我收到错误 "Program .... File: minkernel\crts\ucrt\src\appcrt\convert\isctype.cpp ... "Expression c >= -1 && c <= 255"" 我认为这与这条线没有正确传回数据有关。

问题在于为该图像分配(和释放)内存;谁对此负责?

您不能(不应该)在一个模块中分配内存并在另一个模块中释放它。

您的两个选择是:

  1. 在调用方分配足够大的缓冲区,让 DLL 使用它 utility::conversions::from_base64()。这里的问题是:什么足够大?某些 Win APIs 提供了一种额外的方法来查询所需的大小。不适合这种情况,因为 DLL 要么必须第二次获取该图像,要么(无限期地)持有它直到您请求它。
  2. 在 DLL 中分配所需的缓冲区并 return 指向它的指针。您需要确保在调用者请求释放它之前不会释放它(在单独的 API 中)。

给出要求,没有任何方法可以避免分配更多内存和复制字节。您不能直接使用向量,因为它是 GetInfoAndPicture 函数的本地向量,并且会在该函数退出时被销毁。

如果我正确理解 API 那么这就是您需要做的

//*image = new char[imageBytes.size()];  //use this if caller calls delete[] to deallocate memory
*image = (char*)malloc(imageBytes.size());  //use this if caller calls free(image) to deallocate memory
std::copy(imageBytes.begin(), imageBytes.end(), *image);
*imageSize = imageBytes.size();

也许您的 utility::conversions 函数中有一些方法可以直接解码为字符数组而不是矢量,但只有您知道。