C implementation for C ++ strings and string vector

I have some C ++ APIs as shown below:

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

I want to call this API code C. How can I provide a C shell for this?

std::string str =>

I can use char * for std :: string

&

std::vector<std::string> vecofstr => an array of char * for a string vector of type

char * arrOfstrings [SIZE];

+7
c ++ string arrays vector
source share
2 answers

Here's what the corresponding C header (and its implementation in C ++) might 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 C code will use null-terminated strings for all string arguments. If this is not the case, the cAPI1 parameters should be changed accordingly (ideally based on which string representation is actually used by the C code).

+19
source share

1.api.h

 #ifndef API_H_ #define API_H_ #include <vector> #include <string> void api1(std::string& str, std::vector<std::string>& vecofstr); #endif 

0.2. api.cpp

 #include "api.h" #include <iostream> void api1(std::string& str, std::vector<std::string>& vecofstr) { std::cout << str << std::endl; for (size_t i=0; i<vecofstr.size(); i++) { std::cout << vecofstr[i] << std::endl; } } 

3.wrapper.h

 #ifndef WRAPPER_H_ #define WRAPPER_H_ #define SIZE 2 #ifdef __cplusplus extern "C" { #endif extern void wrapper1(char* p, char* [SIZE]); #ifdef __cplusplus }; #endif #endif 

4.wrapper.cpp

 #include <string> #include "wrapper.h" #include "api.h" #ifdef __cplusplus extern "C" { #endif void wrapper1(char* p, char* ps[SIZE]) { std::string str(p); std::vector<std::string> vecofstr; for (size_t idx=0; idx<SIZE; idx++) { vecofstr.push_back(ps[idx]); } api1(str, vecofstr); } #ifdef __cplusplus }; #endif 

0.5. test.c

 #include "wrapper.h" int main(void) { char* p = "hello world"; char* ps[] = {"world", "hello"}; wrapper1(p, ps); return 0; } 

0.6. compilation

 gcc -c api.cpp wrapper.cpp gcc test.c -o test wrapper.o api.o -lstdc++ 

0.7. mileage

 ./test hello world world hello 
-3
source share

All Articles