简体   繁体   English

是否可以将结构转换为另一个?

[英]Is it possible to cast struct to another?

Any one could describe how (struct sockaddr *)&server works here? 任何人都可以描述(struct sockaddr *)&server如何在这里工作? Is it possible to cast bigger struct to smaller struct? 是否有可能将更大的结构转换为更小的结构?

See these structs: 看到这些结构:

// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

struct in_addr {
    unsigned long s_addr;          // load with inet_pton()
};

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};

This is the main program: 这是主要计划:

int main(int argc , char *argv[])
 {
        int socket_desc;
        struct sockaddr_in server;

    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }

    server.sin_addr.s_addr = inet_addr("74.125.235.20");
    server.sin_family = AF_INET;
    server.sin_port = htons( 80 );

    //Connect to remote server
    if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        puts("connect error");
        return 1;
    }

    puts("Connected");
    return 0;
}

This is refered as Type Punning . 这被称为Punning类型 Here, both structures have the same size, so there is no question of struct size. 这里,两个结构都具有相同的大小,因此不存在结构大小的问题。 Although you can cast almost anything to anything, doing it with structures is error-prone. 虽然你几乎可以将任何东西投射到任何东西上,但使用结构进行渲染很容易出错。

This is C's form of "inheritance" (notice the quotes). 这是C的“继承”形式(注意引号)。 This works because C does not care about the underlying data in an address, just what you represent it as. 这是有效的,因为C不关心地址中的基础数据,只是你所代表的。

The function determines what structure it actually is by using the sa_family field, and casting it into the proper sockaddr_in inside the function. 该函数通过使用sa_family字段确定它实际上是什么结构,并将其强制转换为函数内部的正确sockaddr_in

你可以将sockaddr_in转换为sockaddr,但是你通常不能将任何结构转换为任何其他结构并假设事情能够正常工作。

In C, it's possible to cast anything to anything. 在C中,可以将任何东西投射到任何东西上。 You could even omit the cast to (struct sockaddr*), and probably just get a compiler warning. 您甚至可以省略转换为(struct sockaddr *),并且可能只是获得编译器警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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