开发者

WSASend : Send int or struct

开发者 https://www.devze.com 2023-01-27 00:48 出处:网络
I would like to use MS function to send data. I didnt find examples where they send other type of data other than const char * .

I would like to use MS function to send data.

I didnt find examples where they send other type of data other than const char * . I tried to send a int, or other, but I failed.

WSASend() and send() both function only tak开发者_StackOverflowe a Char* parameters.

How should i proceed ?

Thanks


Its just a pointer to a buffer, this buffer may contains anything you want.

This char pointer is actually an address to a bytes array, this function requires a length parameter too.

An integer is a 2/4 (short/long) bytes value,

Then if you want to send an integer variable (for example) you have to pass its address, and its length.

WSASend and send are simple functions that send a memory block.

I assume you are talking about C, you have to understand that C's char variables are bytes - 8 bits block, char variables contain any value between 0 and 255.

A pointer to a char var is an address to a byte (which maybe the first cell of a bytes array).

I think thats what confuses you.

I hope you understand.


The const char* parameter indicates that the function is taking a pointer to bytes. Witch really seems to be the result of the original socket api designers being pedantic - C has a generic type to handle any kind of pointer without explicit casts: void*.

You could make a convenience wrapper for send like this - which would allow you to send any (contiguous) thing you can make a pointer to:

int MySend(SOCKET s, const void* buf, int len,int flags)
{
  return send(s,(const char*)buf,len,flags);
}

Using void* in place of char* actually makes the api safer, as it can now detect when you do something stupid:

int x=0x1234;
send(s,(const char*)x,sizeof(x),0); // looks right, but is wrong.
mysend(s,x,sizeof(x),0); // this version correctly fails
mysend(s,&x,sizeof(x),0); // correct - pass a pointer to the buffer to send.

WSASend is a bit more tricky to make a convenience wapper for as you have to pass it an array of structs that contain the char*'s - but again its a case of defining an equivalent struct with const void*'s in place of the const char*'s and then casting the data structures to the WSA types in the convenience wrapper. Get it right once, and the rest of the program becomes much easier to determine correct as you don't need casts everywhere hiding potential bugs.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号