How to let cv::Mat created at specified memory address?

In embeded system cv development using pure C, we usually pre-allocate a continious memory and create data structures in it, and usually don’t allocate other memory when in runtime (except little temp variables on stack) so as to simplify the memory management and less memory fragment which may import logger addressing time and especially cause crash in JNI due to delayed GC. A simple code is like that:

struct Image
{
    ...
};

struct ObjectDetection
{
    ...
};

bool InitObjectDetection(void** p)
{
    *p = malloc(0x1000);
    Image* ip = (Image*)*p;
    ip->width = 0;
    ...
    ObjectDetection* op = (ObjectDetection*)*p+sizeof(Image);
    op->networdStucture = ...;

    
    return true;
}

bool ExecuteObjectDetection(void* p)
{
    ...
}

void FreeObjectDetection(void* p)
{
    free(p);
    p = nullptr;
}

int main()
{
    void* p = nullptr;
    InitObjectDetection(&p);
    ExecuteObjectDetection(p);
    FreeObjectDetection(p);
    return 0;
}

Now let’s turn to modern C++, is there any way to do the same thing with OpenCV? Seems cv::Mat will auto alloc memory when constructed and we cannot specify where we want it to create.

OpenCV does not support C.

you can create a cv::Mat (RAII/stack) that does now own its memory but uses memory that you give it.

look at cv::Mat data member. You can point it to allocated memory if you properly configure number of channels, image height/width, step size.

crosspost