简体   繁体   English

C ++指向字节数组优化的指针

[英]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: * pVid是这样的:

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

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 . 当前编写代码的方式,循环中的每个分配都会溢出,并在pBuffer提供一些垃圾值,因为您正试图将一个unsigned int分配给BYTE On top of that, you will run off the end of the Image.pVid array because i is counting bytes, not unsigned int s 最重要的是,您将运行Image.pVid数组的末尾,因为i正在计数字节,而不是unsigned int s

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代替:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM