0

back again with a "using C in C++" kind of question. In my experiment to use APR in C++ I am facing a new issue. The C++ header file:

#ifndef TEST_STRINGCOMMONS_H_
#define TEST_STRINGCOMMONS_H_

namespace test {
class StringCommons {
public:
    static char* substr_offset_length(apr_pool_t *pool, const char* input,
                                  apr_size_t offset, apr_size_t length);
};
} /* namespace test */
#endif /* TEST_STRINGCOMMONS_H_ */

and the C++ implementation of it:

namespace test {
...
char* substr_offset_length(apr_pool_t *pool, const char* input, apr_size_t offset, apr_size_t length)
{
    apr_size_t *input_length = apr_pcalloc(pool, sizeof(apr_size_t));
...
}

} // namespace test

By compiling this class I get the error:

error: invalid conversion from ‘void*’ to ‘test::apr_size_t* {aka long unsigned int*}’ [-fpermissive]

I would like to know what is wrong with this code. Somebody help me please.

Best regards, SK

Kilátó
  • 403
  • 3
  • 10
  • 19
  • Instead of "compiling C as C++", compile C as C, and compile C++ as C++, and let the linker do the joining – M.M Mar 31 '14 at 04:16

2 Answers2

1

apr_pcalloc returns a void*, which you may need to static_cast to your desired type (apt_size_t* in this case).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

In C++, any pointer can be implicitly converted to void* (just as in C). But unlike C, in C++ a pointer of void* type can't be implicitly converted to int*, or void**, or std::string*, or whatever.

The solution is reinterpret_cast:

apr_size_t *input_length = reinterpret_cast<apr_size_t *>(apr_pcalloc(pool, sizeof(apr_size_t)));

Although why would anybody want to allocate a lonely long on the heap is beyond me.

Joker_vD
  • 3,715
  • 1
  • 28
  • 42