如何将char*转换为std::string

How to convert char* to std::string

本文关键字:std 转换 string char      更新时间:2023-10-16

下面的函数返回一个char*:

 // Returns the pointer to the actual packet data.
 // @param pkt_handle The buffer handle.
 // @param queue      The queue from which the packet is arrived or destined.
 // @return           The pointer on success, NULL otherwise.
u_char * pfring_zc_pkt_buff_data(
  pfring_zc_pkt_buff *pkt_handle,
  pfring_zc_queue *queue
);

和下面的函数接受字符串作为输入。

  template<class ...Args>
  bool write(Args&&... recordArgs) {
    auto const currentWrite = writeIndex_.load(std::memory_order_relaxed);
    auto nextRecord = currentWrite + 1;
    if (nextRecord == size_) {
      nextRecord = 0;
    }
    if (nextRecord != readIndex_.load(std::memory_order_acquire)) {
      new (&records_[currentWrite]) T(std::forward<Args>(recordArgs)...);
      writeIndex_.store(nextRecord, std::memory_order_release);
      return true;
    }
    // queue is full
    return false;
  }

我不能更改函数代码。u_char * pfring_zc_pkt_buff_data返回指向pfring_zc_recv_pkt(zq, &buffers[lru], 1)捕获的实际数据包的指针。

我需要将部分数据包保存到缓冲区,所以我必须将u_char*转换为字符串*有许多类似的问题,如:

如何将unsigned char*转换为std::string ?

如何将const char *转换为std::string

如何将字符转换为字符串?

我的问题找不到合适的答案。

这是我的一些代码。

void run() {
    int i=0,n;
    char buf[_snapLengthConnection + _ConnectionHeaderSize];    
    for(;;){
        if(likely(pfring_zc_recv_pkt(zq, &buffers[lru], wait_for_packet)>= 0)) {               
            u_char *pkt_data = pfring_zc_pkt_buff_data(buffers[lru], zq);        
            pfring_print_pkt(buf, sizeof(buf), pkt_data, buffers[lru]->len,sizeof(buf));       
            std::string *payload;
            //need to save buf to payload
            // how do i copy buf to payload?               
            std::cout<< payload<<"=="<<std::endl;               
            _activeBuffer->queue->write(payload);    
        } 
     }
}

如何将u_char*转换为字符串?

操作系统:Ubuntu

std::string有一个构造函数:

const char *str = "Shravan Kumar";
std::string str(str);

请确保您的char *不是NULL,否则将导致未定义的行为。