简体   繁体   中英

How to write generic pointer on socket?

How can a void* be written on a tcp socket in C++? 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:

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.

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. But make sure to take the sizeof of your type, not the sizeof of a pointer to your type. Ie, if the type of your object is YourClass , use sizeof(YourClass) , not sizeof(YourClass*) or even sizeof(void*) !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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