【问题标题】:C implementation for C++ strings & vector of stringsC++ 字符串和字符串向量的 C 实现
【发布时间】:2017-09-04 07:38:47
【问题描述】:

我有一些 C++ API,如下所示:

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

我想从 C 代码中调用这个 API。我如何为此提供 C 包装器?

std::string str =>

我可能可以将 char* 用于 std::string

&

std::vector&lt;std::string&gt; vecofstr => 字符串向量的 char* 数组,如

char* arrOfstrings[SIZE];

【问题讨论】:

  • 嗯,std::vector 作为副本传入...
  • 是的,也许...
  • 我会使用:API1_Wrapper(const char* str, const char** vecofstr, size_t vecSize);
  • ^ 那个,包裹在extern "C" {}.

标签: c++ arrays string vector


【解决方案1】:

这就是相应的 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 代码实际使用的字符串表示形式)。

【讨论】:

  • 这里假设str 和vecofstr 的元素都是C 字符串(即以零值字符结尾)。否则,您的代码会产生未定义的行为。
  • 我试图理解 C 实现中的语法:{vecofstr + vecofstrSize}。如何将其分配给 C++ 对应的 vector::string ?
  • @codeLover - 如果你不确定如何初始化一个向量,你的第一站应该是documentation of std::vector's constructors
  • @codeLover 请注意,正如答案所说,函数 cAPI1 需要 C++ 实现,而不是 C 实现。语法是{vec, vec + size},它只是调用std::vector的2-iterator构造函数。
  • 在现代 C 中,您宁愿写成 void cAPI1(const char *str, const, size_t vSize, char* vecofstr[vSize])。指针对指针通常表示你打算返回一个指针,所以它具有误导性。
【解决方案2】:

1.api.h

#ifndef API_H_
#define API_H_
#include <vector>
#include <string>

void api1(std::string& str, std::vector<std::string>& vecofstr);

#endif

.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

.5。测试.c

#include "wrapper.h"

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

.6。编译

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

.7。运行

./test
hello world
world
hello

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多