简体   繁体   中英

How do I pass a pointer to a struct from a library function back into my main.c program?

I have a function and a struct defined in my library. I want the function to return a pointer to the struct. When I try to compile the program and the library I get the following error:

error: incomplete definition of type 'struct _bmpfile'
    printf("file size: %d", bmp->header.filesz);
                            ~~~^
/usr/local/include/bmpfile.h:116:16: note: forward declaration of 'struct _bmpfile'

typedef struct _bmpfile bmpfile_t;

The struct is declared in bmpfile.h and then defined in bmpfile.c. My program, main.c, calls the following function which should return a bmpfile_t:

bmp = bmp_create_from_file(filename);

bmpfile_t*
bmp_create_from_file(const char *filename)
{
    FILE *fp;

    fp = fopen(filename, "r");
    if (fp == NULL) perror("error");

    bmpfile_t *bmp = (bmpfile_t *)malloc(sizeof(bmpfile_t));

    bmp_get_header_from_file(fp, bmp);
    bmp_get_dib_from_file(fp, bmp);
    bmp_get_pixels_from_file(fp, bmp);
    fclose(fp);
    return bmp;
}

That printf call will need a full definition of the struct before it can access the members.

It's common for libraries to declare only the name of the struct in the header file, so files including the header can manipulate pointers to the type without knowing the contents. The struct is considered opaque . This is roughly the C equivalent to declaring all members private.

For hacking purposes, you can paste the structure definition into your main file and peek at the values in the struct. But for "production" code, don't ever do this, period, end-of-sentence (unless you have a really really really good reason, but be prepared to explain this reason to anyone who may see the code!).

As paulsm4 says, you can use bmp_header_t bmp_get_header(bmpfile_t *bmp); to get a header object that you can access.

The problem is that bmpfile_t is declared as an "opaque struct".

Solution: simply call bmp_get_header()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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