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

标签 c++ c qt gcc

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

在做了一些研究之后herehere ,我注意到用 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);
}

最佳答案

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

正如我们所见,malloc_wrapper()函数返回 void *和你的 newflow->ndpi_flow类型为 ndpi_flow_struct* .所以在编译时使用 c++编译器,你必须添加 cast , 喜欢

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

强制编译器相信 malloc_wrapper() 的返回值类型为 (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 .

关于c++ - 如何将 void* 转换为 foo* 以符合 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29386468/

相关文章:

c - 如果一段时间后没有输入,则退出 for 循环

linux - 创建针对不同 Linux 发行版的 Qt 应用程序

Qt5.7 qmake; "The system cannot find the path specified."是什么意思以及如何修复它?

QML TreeView 的 C++ 模型

c++ - 我应该坚持使用哪种语言

c++ - 分段故障

C++ 11 多线程 : Why the result is not always the same?

C语言在网口抓包

c++ - gmock ElementsAreArray() Matcher 在 gmock-matchers.h 中给出编译器错误

c - 无法确定简单多线程程序中的错误