简体   繁体   English

C ++字符串和字符串向量的C实现

[英]C implementation for C++ strings & vector of strings

I've some C++ APIs like below: 我有一些C ++ API如下:

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

I want to call this API from a C code. 我想从C代码中调用此API。 How can i provide a C wrapper for this ? 我怎样才能为此提供C包装?

std::string str => std::string str =>

I can probably use char* for std::string 我可以使用char *来表示std :: string

&

std::vector<std::string> vecofstr => array of char* for vector of string like std::vector<std::string> vecofstr =>字符串向量的char *数组

char* arrOfstrings[SIZE]; char * arrOfstrings [SIZE];

This is what the corresponding C header (and its C++ implementation) could look like: 这是相应的C头(及其C ++实现)的样子:

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. 以上假设C代码将对所有字符串参数使用以零结尾的字符串。 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). 如果不是这种情况,则必须相应地修改cAPI1的参数(理想情况下,基于C代码实际使用的字符串表示)。

1.api.h 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. 0.2。 api.cpp 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 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 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. 0.5。 test.c test.c的

#include "wrapper.h"

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

.6. 0.6。 compile

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

.7. 0.7。 run

./test
hello world
world
hello

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM