我有一些 C++ API,如下所示:
API1(std::string str, std::vector<std::string> vecofstr);
我想从 C 代码调用此 API。我如何为此提供 C 包装器?
std::string str
=>
I can probably use char* for std::string
&
std::vector<std::string> vecofstr
=>
字符串 vector 的 char* 数组,如
char* arrOfstrings[SIZE];
最佳答案
这是相应的 C 头文件(及其 C++ 实现)的样子:
声明
#ifdef __cplusplus
extern "C"
#endif
void cAPI1(const char *str, const char * const *vecofstr, size_t vecofstrSize);
实现
extern "C" void cAPI1(const char *str, const char * const *vecofstr, size_t vecofstrSize)
{
API1(str, {vecofstr, vecofstr + vecofstrSize});
}
以上假定 C 代码将对所有字符串参数使用零终止字符串。如果不是这种情况,则必须相应地修改 cAPI1
的参数(最好基于 C 代码实际使用的字符串表示形式)。
关于c++ - C++ 字符串和字符串 vector 的 C 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032386/