如何将 void* 转换为 foo* 以符合 C++?

How to convert void* to foo* to comply with C++?

我正在尝试编译用 C 编写的代码(ndpiReader.c nDPI 库附带的程序,托管 here)。我正在使用 Qt Creator 和 GCC 编译器。

经过一些研究 here and here,我发现用 C++ 编译器编译 C 代码并不是最好的主意。但是我没有得到如何进行此转换并使此代码与 C++ 兼容的答案。

当我尝试 运行 Qt Creator 中的代码时,出现以下错误:

error: invalid conversion from 'void*' to 'ndpi_flow_struct*' [-fpermissive] if((newflow->ndpi_flow = malloc_wrapper(size_flow_struct)) == NULL) { ^

如果需要更多信息来解决问题,请发表评论。我是 C++ 的新手,非常感谢带有链接的详细答案。

编辑:这里是malloc_wrapper()函数的代码

static void *malloc_wrapper(unsigned long size) {
  current_ndpi_memory += size;

  if(current_ndpi_memory > max_ndpi_memory)
    max_ndpi_memory = current_ndpi_memory;

  return malloc(size);
}

通常我们只写

if((newflow->ndpi_flow = (ndpi_flow_struct*)malloc_wrapper(size_flow_struct)) == NULL) { 

您看到此错误是因为在 c++ 中,类型应该完全匹配。

正如我们所见,malloc_wrapper() 函数 return 是一个 void * 而您的 newflow->ndpi_flowndpi_flow_struct* 类型。因此,在使用 c++ 编译器进行编译时,您必须添加 cast,例如

if((newflow->ndpi_flow=(ndpi_flow_struct*)malloc_wrapper(size_flow_struct)) == NULL) { . . . 

强制编译器相信 malloc_wrapper() 的 return 值是 (ndpi_flow_struct*).

类型

甚至更好,static cast<>(记住 C++ 方面),例如

if(( newflow->ndpi_flow = 
                static_cast<ndpi_flow_struct*>malloc_wrapper(size_flow_struct)) == NULL) { . . .

相关阅读:A detailed answer on C++ Casting.