更新时间:2023-01-17 10:42:38
对于任何理智的界面,@iharob 都是正确的 - 明确他/她是你对字符串赋值的误解是正确的.
With any sane interface, @iharob would be right - to be clear he/she is right about you misunderstanding string assignment.
然而,libwebsockets 有点特别".您需要将字符串复制到 malloc()
的数组 LWS_SEND_BUFFER_PRE_PADDING
字节中.libwebsockets 然后覆盖前面的字节.
However, libwebsockets is a bit 'special'. You need to copy the string into the malloc()
'd array LWS_SEND_BUFFER_PRE_PADDING
bytes in. libwebsockets then overwrites the preceding bytes.
所以你想要类似的东西(假设你没有尝试在字符串上发送终止零):
So you want something like (assuming you are not trying to send the terminating zero on the string):
char *text = "Hello World!";
int len = strlen (text);
unsigned char *buf = malloc(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING);
/* copy string but not terminating NUL */
memcpy (buf + LWS_SEND_BUFFER_PRE_PADDING, text, len );
libwebsocket_write(wsi, buf + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
free(buf);
如果您还想发送 NUL
:
char *text = "Hello World!";
int len = strlen (text) + 1;
unsigned char *buf = malloc(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING);
/* copy string including terminating NUL */
memcpy (buf + LWS_SEND_BUFFER_PRE_PADDING, text, len );
libwebsocket_write(wsi, buf + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
free(buf);