问题描述
我遇到了一个套接字编程教程,在该教程中引用了它
I came across a socket programming tutorial in which it is quoted
我不知道如何将sockaddr_in强制转换为sockaddr.将 Big 类型的指针强制转换为 Small 类型的指针应具有UD行为.
I dont understand how can sockaddr_in be cast to sockaddr. Casting a pointer of Big type to Small type should give UD behavior.
struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};
struct sockaddr_in {
short int sin_family; // Address family, AF_INET
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8]; // Same size as struct sockaddr
};
如何不对演员表进行不确定的定义?将它们相互投射是不安全的吗?
How can the cast not be undefined? Isn't it unsafe to cast these to each other?
如果我的A类只有两个整数,而B类则只有4个整数.如果我有一个类型为B的指针并将其强制转换为类型A,那么请确保我可以获取前两个元素.但是,如果类A具有首先声明的2个字符和之后声明的2个整数,则指针将无法正确获取值,因为在这种情况下,对象布局将有所不同.
If i have a class A having only two ints and class B having 4 ints. And if i have a pointer of type B and i cast it to type A then sure i can fetch the first two elements. But if class A has 2 chars declared first and 2 ints declared later then the pointers would not right fetch the values since the object layout in this case would be different.
class Anu
{
public:
char a;
int b;
Anu()
{
a='a';
}
};
class Anurag
{
public:
Anurag() { a=4;}
int a;
int b;
int c;
int d;
};
int main()
{
Anu objanu;
Anurag objanurag;
Anurag *ptrAnurag= &objanurag;
ptrAnurag= (Anurag*)&objanu;
cout<<ptrAnurag->a; //Some weird value here
return 0;
}
假设我更改示例,以便通过调整变量类型使两个类具有相同的大小...即使大小保持不变,对象布局仍可能不同.
Assuming i change the example so that both classes have same size by adjusting the variables types...still the object layout might be different even though the size remains the same.
推荐答案
我将在@gsamaras答案中加入未定义行为"并不总是意味着坏事即将发生的信息.未定义行为实际上是在说:如果发生XYZ,我们将不提供下一步的规范."
I'll add to @gsamaras answer by saying that Undefined Behaviour doesn't always means that bad things are about to happen. Undefined Behaviour actually says "we* don't provide any specifications on what should happen next if XYZ occurs".
(* C ++标准).
(*the C++ standard).
这是操作系统发生的地方,说它是我们定义的".
this is the place where the OS takes place and say "it is defined by us".
尽管标准强制转换不相关的结构(sockaddr_in
,sockaddr
)可能是未定义的行为,但OS API会指定它对它们的API有效.
although casting unrelated structs (sockaddr_in
,sockaddr
) may be undefined behaviour by the standard, the OS API specify that it is valid with their API.
这篇关于在sockaddr和sockaddr_in之间进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!