简体   繁体   中英

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

I am trying to compile a code written in C (ndpiReader.c program that comes with nDPI library, hosted here ). I'm using Qt Creator and GCC compiler.

After doing some research here and here , I notice that compiling C code with C++ compiler is not the best idea. But I didn't get the answer of how to do this conversion and make this code C++ compatible.

When I try to run the code in Qt Creator I get the error bellow:

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

If more info is needed to solve the problem please leave a comment. I'm new to C++ so detailed answers with links are so much appreciated.

Edit: here is malloc_wrapper() function's code

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);
}

You're seeing this error because in c++ , types should have an exact match.

As we can see, the malloc_wrapper() function returns a void * and your newflow->ndpi_flow is of type ndpi_flow_struct* . So while compiling using c++ compiler, you've to add the cast , like

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

to force the compiler in believing that the return value of malloc_wrapper() is of type (ndpi_flow_struct*) .

or even better, the static cast<> (keeping in mind the C++ aspect), like

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

Related Reading: A detailed answer on C++ Casting .

通常,我们只写

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM