Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling C++ methods from C

Tags:

c++

c

So it's been a while since I've used straight C. And I'm on a project where I'm working on an API in C++. Most of these methods are just C anyway, and all of the return values are C structures. Except one. One method I need to return a vector<string>. Now here's my question. Is C++ methods/libraries/whatever callable from C? I ask because I don't know if the people using the API are going to be writing in C or C++, and I feel like I should be returning only C structures. That would require me to return a char**, right?

I hope that made sense, if not:

tl;dr version - Can I call a C++ method from C if it returns a C structure, and if so is the best (only?) equivalent return value of vector<string> -> char**?

Update: The C++ methods are simply global methods. There's no classes or object oriented stuff in them. The ONLY thing that's specific to C++ other than my vector question is a few stringstreams

like image 914
Falmarri Avatar asked Aug 04 '10 06:08

Falmarri


1 Answers

No, C cannot use C++ features that are not also available in C. However, C code can make use of C++ code indirectly. For example, you can implement a C function using C++, and you can use opaque types in the interface so that the signature uses void*, but the implementation uses a C++ class.

The equivalent of vector<string> in C is probably closer to:

 typedef const char* c_string_type;
 typedef struct c_string_array {
     c_string_type* c_strings;
     int c_strings_count;
  } c_string_array_t;

With opaque types, you would have something along the lines of:

 typedef void* c_string_array_t;
 int c_string_array_length(c_string_array_t array);
 const char* c_string_array_get(c_string_array_t array, int index);

You could then secretly (in the C++ implementation) cast std::vector* to void*.

like image 197
Michael Aaron Safyan Avatar answered Sep 30 '22 17:09

Michael Aaron Safyan