C 函数转换为 C++

C function conversion to c++

我在尝试将用 C 编写的回调调整为 C++ 时遇到 C 语言问题。编译器显示以下错误:

error C2664: 'fread' : cannot convert parameter 4 from 'void *' to 'FILE*'
1>Conversion from 'void*' to pointer to non-'void' requires an explicit cast

我发现这个size_t retcode = fread(ptr, size, nmemb, stream) 需要 cast。我试过了,但没有任何效果。这是代码:

static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
    curl_off_t nread;
    size_t retcode = fread(ptr, size, nmemb, stream);
    nread = (curl_off_t)retcode;
    fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T
            " bytes from file\n", nread);
    return retcode;
}
fread(ptr, size, nmemb, static_cast<FILE*>(stream))

这是一个完全有效的 C 代码示例,但它不是有效的 C++。 C 标准明确允许 void* 到任何指针类型(和返回)的隐式类型转换。

§6.3.2.3 ¶ 2:

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

但是C++只允许在void*的方向:

§4.11 ¶ 2:

A prvalue of type “pointer to cv T”, where T is an object type, can be converted to a prvalue of type “pointer to cv void”. The pointer value ([basic.compound]) is unchanged by this conversion.

另一个方向只能通过转换才能实现。