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

m.r*_*226 0 c++ casting stdstring

以下函数返回一个 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
);
Run Code Online (Sandbox Code Playgroud)

以下函数将字符串作为输入。

  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;
  }
Run Code Online (Sandbox Code Playgroud)

我无法更改函数代码。的u_char * pfring_zc_pkt_buff_data指针返回到由捕捉到的实际的分组pfring_zc_recv_pkt(zq, &buffers[lru], 1)

我需要将数据包的一部分保存到缓冲区,所以我必须将 u_char* 转换为 string* 。有很多类似的问题,例如:

如何在 C++ 中将 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);    
        } 
     }

}
Run Code Online (Sandbox Code Playgroud)

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

操作系统: Ubuntu

gcc 版本:4.8.2

Shr*_*n40 6

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

const char *str = "Shravan Kumar";
std::string str(str);
Run Code Online (Sandbox Code Playgroud)

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