Search code examples
c++cjpegijg

JPEG support with ijg - getting access violation


I was recently trying to update my game to store graphics in compressed formats (JPEG and PNG).

Whilst I ended up settling on a different library, my initial attempt was to incorporate ijg to do JPEG decompression. However, I was unable to get even the simplest console application to work and am wondering if anyone might be able to shed some light on the reasons why.

Here is my code, which is linked to the jpeg.lib that is part of the ijg packages:

#include "stdafx.h"
#include <stdio.h>
#include <assert.h>
#include <jpeglib.h>

int _tmain(int argc, _TCHAR* argv[])
{
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    JSAMPARRAY buffer;
    int row_stride;

    //initialize error handling
    cinfo.err = jpeg_std_error(&jerr);

    //initialize the decompression
    jpeg_create_decompress(&cinfo);

    FILE* infile;
    errno_t err = fopen_s(&infile, "..\\Sample.jpg", "rb");
    assert(err == 0);

    //specify the input
    jpeg_stdio_src(&cinfo, infile);

    //read headers
    (void) jpeg_read_header(&cinfo, TRUE);

    return 0;
}

The problem is that the call to jpeg_read_header() fails with an access violation:

Unhandled exception at 0x7c91b1fa (ntdll.dll) in JPEGTest.exe: 0xC0000005: Access violation writing location 0x00000010.

Does anyone have any ideas what I might be doing wrong?


Solution

  • I've just encountered the same problem (although I was trying to encode an image). Apparently, FILE* are not portable between DLLs so you can't use any libjpeg API that takes a FILE* as a parameter.

    There are several solutions, but they all come down to having to rebuild the library:

    • Build the library as a static lib, and link it to your application. This is what I did, and it solved my problem.
    • Move the source/destination handlers out of libjpeg and into your application. Then you could build libjpeg as either a static lib or a DLL, whichever suits you. I'm not sure whether this would work, but it is the suggested solution in the "install.doc" file distributed with the source code.