Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a struct using the c style while using the g++ compiler?

Tags:

c++

c

struct

fuse

Generally, in order to initialize a struct in c, we could only specify part of the fields. Like below:

static struct fuse_operations hello_oper = {
    .getattr    = hello_getattr,
    .readdir    = hello_readdir,
    .open       = hello_open,
    .read       = hello_read,
};

However, in C++, we should initialize the variables in the struct without naming the fields. Now, what if I would like to initialize a struct using the c style while using the g++ compiler, how to accomplish this? PS: the reason I need to do this is that the struct fuse_operations has too many fields in it.

like image 815
injoy Avatar asked Aug 25 '12 13:08

injoy


2 Answers

You wrote:

   static struct fuse_operations hello_oper = {
       .getattr    = hello_getattr,
       .readdir    = hello_readdir,
       .open       = hello_open,
       .read       = hello_read,
   };

Generally, in order to initialize a struct in c, we could only specify part of the fields [...] However, in C++, we should initialize the variables in the struct without naming the fields. Now, what if I would like to initialize a struct using the c style while using the g++ compiler, how to accomplish this? PS: the reason I need to do this is that the struct fuse_operations has too many fields in it.

My solution was to specialize the struct with a constructor:

struct hello_fuse_operations:fuse_operations
{
    hello_fuse_operations ()
    {
        getattr    = hello_getattr;
        readdir    = hello_readdir;
        open       = hello_open;
        read       = hello_read;
    }
}

Then declare a static instance of the new struct:

static struct hello_fuse_operations hello_oper;

Testing worked OK for me (but this depends on the memory layout of the C-struct and C++-struct to be the same -- not sure that's guaranteed)

* UPDATE *

Though this approach worked fine in practice, I have subsequently converted my code to use a utility class, i.e., a class with a single static 'initialize' method that takes a reference to a fuse_operation struct and initializes it. This avoids any possible uncertainty regarding memory layout, and would be my recommended approach in general.

like image 56
Don Doerner Avatar answered Oct 20 '22 01:10

Don Doerner


Unfortunately, even the C++11 version of the C++ standard lacks the designated initializers feature of C99.

like image 22
Sergey Kalinichenko Avatar answered Oct 20 '22 00:10

Sergey Kalinichenko