tmighty
tmighty

Reputation: 11419

C++ Pointer to byte array optimization

I am currently using this approach to copy some byte values over:

    for (int i = 0; i < (iLen + 1); i++)
    {
        *(pBuffer + i) = Image.pVid[i];
    }

I would like to ask if there is a way to copy these values over in one go, perhaps by using memcopy to gain more speed.

The entire code is:

extern "C" __declspec(dllexport) int __stdcall GetCameraImage(BYTE pBuffer[], int Type, int uWidth, int uHeight)
{
    CameraImage Image;

    int ret;

    Image.pVid = (unsigned int*)malloc(4 * uWidth*uHeight);
    ret = stGetCameraImage(&Image, 1, uWidth, uHeight);
    if (ret == ERR_SUCCESS)
    {
        int iLen = (4 * uWidth * uHeight);

        for (int i = 0; i < (iLen + 1); i++)
        {
            *(pBuffer + i) = Image.pVid[i];
        }

        ////print(“ImageType = %d, width = %d, height = %d”, Image.Type, Image.Width,
        ////    Image.Height);
        ////print(“First Pixel : B = %d, G = %d, R = %d”, Image.pVid[0], Image.pVid[1],
        ////    Image.pVid[2]);
        ////print(“Second Pixel : B = %d, G = %d, R = %d”, Image.pVid[4], Image.pVid[5],
        ////    Image.pVid[6]);
    }

    free(Image.pVid);

    return ret;
}

Edit:
*pVid is this:

unsigned int *pVid;             // pointer to image data (Format RGB32...)

Upvotes: 1

Views: 104

Answers (1)

Wes Cumberland
Wes Cumberland

Reputation: 1338

The way your code is currently written, each assignment in your loop will overflow and give you some garbage value in pBuffer because you're trying to assign an unsigned int to a BYTE. On top of that, you will run off the end of the Image.pVid array because i is counting bytes, not unsigned ints

You could fix your code by doing this:

*(pBuffer + i) = ((BYTE*)Image.pVid)[i];

But that is pretty inefficient. Better to move whole words at a time, or you could just use memcpy instead:

memcpy(pBuffer,Image.pVid,iLen)  //pBuffer must be at least iLen bytes long

Upvotes: 1

Related Questions