Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing C++ struct to library expecting C struct

Tags:

c++

c

linux

struct

I am writing a C++ program in Linux and need to use an older library written in C. The library uses C structs for passing information in and out of functions, and these structs are byte aligned (no padding).

My understanding is that a struct in C++ is actually an object, while a struct in C is just a block of memory divided up into individually addressable pieces.

How can I create a C style struct in C++ to pass to the library? (I can't pass an object)

like image 927
TSG Avatar asked Jul 09 '26 19:07

TSG


1 Answers

You're asking two questions here, really...

How can I create a C style struct in C++?

Instead of

struct foo { /* ... */ };

use

extern "C" {
    struct foo { /* ... */ };
}

This probably won't result in anything different, i.e. a "C++ style struct" and a "C style struct" are usually the same thing, as long as you don't add methods, protected members, and bit fields. Since "extern C" is needed for functions, however, it's reasonable to just surround all code intended for use in C within these braces.

For more details, read: What is the effect of extern "C" in C++? and @AndrewHenle's comment.


I ... need to use a library written in C

I'm paraphrasing an official C++ FAQ item here, telling you to (surprise, surprise) just include the library header within an extern C block, then use whatever's in it like you would if you were writing C:

extern "C" {
  // Get declaration for `struct foo` and for `void f(struct foo)`
  #include "my_c_lib.h"
}

int main() {
    struct foo { /* initialization */ } my_foo;
    f(my_foo);
}
like image 51
einpoklum Avatar answered Jul 11 '26 10:07

einpoklum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!