简体   繁体   English

如何在socket上编写通用指针?

[英]How to write generic pointer on socket?

How can a void* be written on a tcp socket in C++? 如何在C ++中的tcp套接字上写入void *? Especially, do I need to know the type since I cannot know its data size otherwise? 特别是,我需要知道类型,否则我不知道它的数据大小?

In this example, I wouldn't know the data size of buf: 在这个例子中,我不知道buf的数据大小:

foo(const void *buf, int socket){
int n= write(socket , buf, ???);
}

Of course you need to know the size of the object to be written. 当然,您需要知道要写入的对象的大小。 You do not have to know the exact type, but at least its byte size. 您不必知道确切的类型,但至少要知道它的字节大小。 C++ cannot smell how long the object is that is to be written. C ++无法闻到要写入的对象有多长。

If you know the type it should be no problem to pass the length to your function by just using the sizeof operator on it. 如果您知道类型,只需在其上使用sizeof运算符就可以将长度传递给您的函数。 But make sure to take the sizeof of your type, not the sizeof of a pointer to your type. 但要确保采取sizeof你的类型,而不是sizeof的一个指针类型。 Ie, if the type of your object is YourClass , use sizeof(YourClass) , not sizeof(YourClass*) or even sizeof(void*) ! 即,如果您的对象类型是YourClass ,请使用sizeof(YourClass) ,而不是sizeof(YourClass*)或甚至sizeof(void*)

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

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