Poka Yoke
Poka Yoke

Reputation: 403

Access violation OpenCV C++ dll

I'm new to c++, I get the access violation exception whenever I try to construct an object the constructor is as follows

Image::Image( IplImage* pIplImage, bool bDestroy )
    : m_bOwned( bDestroy )
{
    memcpy( static_cast< IplImage* >( this ), pIplImage, sizeof( IplImage ) );

    if ( bDestroy ) 
        cvReleaseImageHeader( &pIplImage );

}

and the destructor is

Image::~Image()
{
    if ( m_bOwned )
        cvFree( reinterpret_cast< void** >( &imageDataOrigin ) );
}

EDIT 1: Class definition

class VISION_EXPORT Image
    : public IplImage
    , private boost::noncopyable
{
public:

explicit Image( IplImage* pIplImage, bool bDestroy = true );
~Image();
private:    
bool m_bOwned;
};

It was working before, but now when I export it as dll.. it doesn't work any more. Can you help me?

Upvotes: 0

Views: 723

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67479

You can't do a memcpy() that writes to the memory pointed by the this pointer. When you do that you trash the internal structure of the object. Instead, what you should do is add a member variable to your Image class. For example:

class Image {
protected:
    pIplImage* m_pImage;
    bool m_bOwned;
// ... whatever else you need here ...
};

Then your implementation could be something like this:

Image::Image( IplImage* pIplImage, bool bDestroy )
: m_pImage(pIplImage), m_bOwned( bDestroy )
{
}

Image::~Image()
{
    if ( m_bOwned )
        cvReleaseImage(m_pImage);
}

As you see above, I don't think you need to copy any data. The code that instantiates this class decides if it wants to pass ownership of the image to the class or not, but either way the Image class just copies the pointer.

Edit: after looking at your code I think I have an idea of what could be wrong. The IplImage pointer passed to the constructor was allocated by the main application and deleted by the DLL. I bet the problem is caused by the two different allocators acting on the same block of memory. You should make sure that memory is allocated and deallocated by the same allocation functions. You may even have OpenCV linked against your main app and also against your DLL, and these are two separate instances of the same library.

Edit #2: See this article for a deeper explanation of the problem. As I said in the comments, if you want to avoid this problem you will need to reorganize your code to avoid cross-module memory allocation/deallocation.

Upvotes: 2

Related Questions