简体   繁体   English

如何从C中的void *缓冲区存储和访问整数和void *?

[英]How to store and access integers and void* from a void* buffer in C?

I am a relatively new C programmer and I have the following problem: 我是一个相对较新的C程序员,我有以下问题:

void someFunction(int sizeOfArg1, void* arg1, int sizeOfArg2, void* arg2)
{
    // Buffer to store sizeOfArg1, arg1, sizeOfArg2, arg2
    void* buffer = malloc(sizeof(int) + sizeof(int) + sizeOfArg1 + sizeOfArg2);

    // How to store variables into buffer and access again?
    ...
}

Basically, what I want to do is to store the arguments to someFunction into a void* buffer and access it again later. 基本上,我想要做的是将someFunction的参数存储到void *缓冲区中,稍后再次访问它。 This includes storing sizeOfArg1, arg1, sizeOfArg2, and arg2. 这包括存储sizeOfArg1,arg1,sizeOfArg2和arg2。

Here, sizeOfArg1 is the size in bytes of arg1 and sizeOfArg2 is the size in bytes of arg2. 这里,sizeOfArg1是arg1的字节大小,sizeOfArg2是arg2的字节大小。 arg1 and arg2 are void* pointers. arg1和arg2是void *指针。

For single variables, I understand that you can use memcpy() or strlen() (if argument is a string). 对于单个变量,我知道你可以使用memcpy()或strlen()(如果参数是一个字符串)。 Also, if all arguments are of a single defined type, I understand that pointer arithmetic can be used to store the variables. 此外,如果所有参数都是单个定义的类型,我理解指针算法可用于存储变量。 However, what I want to do is to store and retrieve each of these values later. 但是,我想要做的是稍后存储和检索每个值。

The reason why I am trying to solve this problem is because I need to pass the buffer into the sendto() function in order to send some information from a client to server via UDP. 我试图解决这个问题的原因是因为我需要将缓冲区传递给sendto()函数,以便通过UDP从客户端向服务器发送一些信息。 The sendto() function accepts a void* buf argument. sendto()函数接受void * buf参数。

I've looked at various sources online, which state that pointer arithmetic on void* is not advisable due to alignment issues and I haven't been able to figure out how to solve this problem from the sources I've looked at for several hours. 我在网上查看了各种来源,其中指出由于对齐问题,无法使用void *上的指针算法,我无法从我看了几个小时的来源中弄清楚如何解决这个问题。

Any help would be appreciated. 任何帮助,将不胜感激。

Use a char buffer instead. 请改用char缓冲区。

#include <stdint.h>  // uint32_t

void func(uint32_t size1, void *arg1, uint32_t size2, void *arg2) {

  uint32_t nsize1 = htonl(size1), nsize2 = htonl(size2);
  uint32_t size = sizeof(size1) + sizeof(size2) + size1 + size2;
  char *buf = malloc(size);

  memcpy(buf,                         &nsize1, sizeof(nsize1));
  memcpy(buf + sizeof(size1),         arg1,    size1);
  memcpy(buf + sizeof(size1) + size1, &nsize2, sizeof(nsize2));
  memcpy(buf + size - size2,          arg2,    size2);

  // sock and dest_addr need to come from somewhere
  sendto(sock, buf, size, 0, dest_addr, sizeof(dest_addr));

  free(buf);
}

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

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