2

I have a header that defines c style structs that are to be passed over a boundary on a c++ DLL. This header and DLL will potentially be used by c++, java and c applications. I want to initialise these structs in someway that allows the user to specify a subset of the parameters, and the rest will be given defaults.

I was thinking of creating a series of initialise functions in the header, which would take a reference to the struct they will initialise along with parameters for all members that can be set. The "initialise" functions would use overloading (based on the struct reference passed in) to ensure the correct one was called. I also planned on using default parameters to set the defaults. The functions would have to be gobal i guess.

Is this a good approach? Is there a better alternative? thanks

pingu
  • 8,719
  • 12
  • 50
  • 84
  • 3
    C doesn't support method overloading. You have to use different function names for a C API, or otherwise abstract all of your functions behind a single function with the same parameter list. You might also find [this question](http://stackoverflow.com/questions/479207/function-overloading-in-c) helpful. – Michael Madsen Jan 23 '12 at 14:21
  • You can add function prototypes in the header file, but the actual functions should preferably be placed in a source file. Also remember to declare the functions as `extern "C"` so C++ won't mangle their names. Besides that it's not a bad approach. – Some programmer dude Jan 23 '12 at 14:21
  • @Joachim, thanks, I thought to put the implentations in the header so they would be available to any third-party of the DLL to use, is this sensible? – pingu Jan 23 '12 at 14:30
  • 1
    Third parties can still link to your "library". If you put functions in the header, you also has to make them _inline_ as otherwise you might get multiple definition errors when linking. – Some programmer dude Jan 23 '12 at 14:34
  • If the struct should be compiled by a 3rd party, I suspect you will have to address alignment issues somehow. The struct inside the DLL may not necessarily use the same alignment as a struct compiled in the application calling the DLL. #pragma pack or similar might be useful. – Lundin Jan 23 '12 at 15:38

1 Answers1

6

You could add a function that returns a default initialized structure :

struct abc
{
  int a;
  float b;
  char c;
};

abc GetDefaultAbc()
{
  const abc def = { 1,2.0,3 };
  return def;
};
BЈовић
  • 62,405
  • 41
  • 173
  • 273