Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise C-structs in C++

Tags:

c++

c

struct

dll

I am creating a bunch of C structs so i can encapsulate data to be passed over a dll c interface. The structs have many members, and I want them to have defaults, so that they can be created with only a few members specified.

As I understand it, the structs need to remain c-style, so can't contain constructors. Whats the best way to create them? I was thinking a factory?

like image 264
dangerousdave Avatar asked Feb 21 '23 18:02

dangerousdave


2 Answers

struct Foo {
    static Foo make_default ();
};

A factory is overkill. You use it when you want to create instances of a given interface, but the runtime type of the implementation isn't statically known at the site of creation.

like image 185
spraff Avatar answered Mar 04 '23 19:03

spraff


The C-Structs can still have member functions. Problems will, however, arise if you start using virtual functions as this necessitates a virtual table somewhere in the struct's memory. Normal member functions (such as a constructor) don't actually add any size to the struct. You can then pass the struct to the DLL with no problems.

like image 44
Goz Avatar answered Mar 04 '23 17:03

Goz