How to cast OpenCV cv::Mat as Void pointer?

960 Views Asked by At

I am using a 3rd party SDK in my project which accepts void * pointer for setting user specific metadata. But my metadata is in cv::Mat format thus I need to cast the cv::Mat as void * pointer as shown here:

void *set_metadata_ptr(cv::Mat frame)
{

  cv::Mat *user_metadata = new cv::Mat();

  frame.copyTo(*user_metadata);

  return (void *)user_metadata;
}

void foo() 
{
  UserMeta *user_meta = /* ... */;
  user_meta->user_meta_data = (void *)set_metadata_ptr(frame);
}

This works good, but many of the OpenCV power users discourage using pointers with cv::Mat as cv::Mat has smart pointer itself. I wonder is there any better way to cast the cv::Mat as void-pointer in my case?

1

There are 1 best solutions below

8
On

Simply create your own wrapper:

class MyWrapper {
public:
    cv::Mat frame;
};

Allocate as you normally would:

MyWrapper *ptr = new MyWrapper();
ptr->frame = myOtherFrame;

Then pass where you need, like:

user_meta->user_meta_data = (void *) ptr;

Note that your approach (mentioned in question) is doing a full copy, but above just keeps a reference to an existing smart-pointer.

One liner version:

We could shorten the usage, into:

user_meta->user_meta_data = (void *) new MyWrapper( frame );

If we had a constructor, like:

class MyWrapper {
public:
    explicit MyWrapper(cv::Mat &frame)
        : frame(frame)
    {}

public:
    cv::Mat frame;
};