c++ - C++ 字符串和字符串 vector 的 C 实现

标签 c++ arrays string vector

我有一些 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});
}

[Live example]

以上假定 C 代码将对所有字符串参数使用零终止字符串。如果不是这种情况,则必须相应地修改 cAPI1 的参数(最好基于 C 代码实际使用的字符串表示形式)。

关于c++ - C++ 字符串和字符串 vector 的 C 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032386/

相关文章:

Python "join"位于字符串两侧?

python - 如何使用 BeautifulSoup 删除表格单元格中的多余内容

c++ - 通过 winsock2 发送 uchar*

c++ - OpenCV C++ 中的透明像素(使用 GrabCut 时)

c# - 在 LINQ C# 中计算数组

java - Arrays.asList() 在java中的实现

javascript - Splice() 不会使数组为空

C++从ifstream读取一个 block 并写入ofstream

C++ cin.fail() 执行并移动到下一行,即使输入是另一种数据类型

string - 按前缀对字符串数组进行分组的高效算法