Question

I would like to know what following syntax does:

func((some_type*) apointer)

Is this a simple type check or does this do something more? Why are there brackets required around the type?

whole example from http://nikhilm.github.com/uvbook/networking.html#tcp:

int main() {
    loop = uv_default_loop();

    uv_tcp_t server;
    uv_tcp_init(loop, &server);

    struct sockaddr_in bind_addr = uv_ip4_addr("0.0.0.0", 7000);
    uv_tcp_bind(&server, bind_addr);

    /* here it is */
    int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection);

    if (r) {
        fprintf(stderr, "Listen error %s\n", uv_err_name(uv_last_error(loop)));
        return 1;
    }
    return uv_run(loop, UV_RUN_DEFAULT);
}

Regards, Bodo

Update:

Could this work?

typedef struct one_t
{
    int counter;

} one_t;

typedef struct two_t
{
    another_t request;
} two_t;

(one_t*) two_t
Was it helpful?

Solution 2

(uv_stream_t*)&server

is a cast. It is used here as a polymorphism emulation in C.

uv_tcp_t may be declared like:

typedef struct uv_tcp_t
{
    uv_stream_t base; //base has to be first member for byte reinterpretation to work

    /*...snip...*/

} uv_tcp_t;

This allows uv_listen to operate on uv_tcp_t as if it was an uv_stream_t variable.

It is common, and (AFAIK) perfectly valid C.

OTHER TIPS

It is known as type cast or type conversion. It is used when you want to cast one of type of data to another type of data.

(some_type) *apointer

This mean that you cast the apointer content to the some_type type

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top