我正在尝试编译用 C 编写的代码(ndpiReader.c 程序随 nDPI 库一起提供,托管 here )。我正在使用 Qt Creator 和 GCC 编译器。
在做了一些研究之后here和 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);
}
最佳答案
您看到此错误是因为在 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) { . . .
关于c++ - 如何将 void* 转换为 foo* 以符合 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29386468/