Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C implementation for C++ strings & vector of strings

I've some C++ APIs like below:

API1(std::string str, std::vector<std::string> vecofstr);

I want to call this API from a C code. How can i provide a C wrapper for this ?

std::string str =>

I can probably use char* for std::string

&

std::vector<std::string> vecofstr => array of char* for vector of string like

char* arrOfstrings[SIZE];

like image 971
codeLover Avatar asked Sep 04 '17 07:09

codeLover


1 Answers

This is what the corresponding C header (and its C++ implementation) could look like:

Declaration

#ifdef __cplusplus
extern "C"
#endif
void cAPI1(const char *str, const char * const *vecofstr, size_t vecofstrSize);

Implementation

extern "C" void cAPI1(const char *str, const char * const *vecofstr, size_t vecofstrSize)
{
  API1(str, {vecofstr, vecofstr + vecofstrSize});
}

[Live example]

The above assumes that the C code will use zero-terminated strings for all string arguments. If that is not the case, the parameters of cAPI1 must be modified accordingly (ideally based on what representation of strings is actually used by the C code).

like image 149
Angew is no longer proud of SO Avatar answered Sep 23 '22 01:09

Angew is no longer proud of SO