Combining C ++ links in C API

I have a header file for what needs to be combined with C ++ and C API. Part C is wrapped in extern "C" , but the declarations themselves are very different from C; eg:

 foo::Bar& Foo_Baz_GetBarOfQux(void *_self, const foo::Qux &qux); 

Is there a way to use it in plain C form? I obviously can't use this header, but maybe I can redo it somehow:

 /* type? */ Foo_Baz_GetBarOfQux(void*, const /* type? */); 

What puzzles me is how to declare the types of these links (if possible).

PS I know that I can write my own C-shell on top of this: I declare classes as opaque structures:

 typedef struct foo_bar foo_bar_t; typedef struct foo_baz foo_baz_t; typedef struct foo_qux foo_qux_t; 

and then write a C-like function that wraps the above function:

 extern "C" foo_bar_t* foo_baz_get_bar_of_qux( foo_baz_t* baz, foo_qux_t* qux) { return (foo_bar_t*) Foo_Baz_GetBarOfQux(baz, *(foo::Qux*)qux); } 

But I am wondering if I can directly use the original Foo_Baz_GetBarOfQux() .

+4
source share
2 answers

No, you cannot directly use Foo_Baz_GetBar() , calls to a member function in c++ implicitly pass the this pointer, which does not exist in your c code.

+7
source

In general, it would be better to use opaque structures.

In the "C" interface of the code, never try to look inside an opaque structure, just dutifully pass pointers.

In the "C ++" part, you should define the structure and actually fill it accordingly (I would avoid blind type casting).

Of course, the โ€œC ++โ€ part should not appear in the โ€œCโ€ header so that it does not confuse the C compiler.

+2
source

Source: https://habr.com/ru/post/906894/


All Articles