Вопрос

I am a relatively new C programmer and I have the following problem:

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. This includes storing sizeOfArg1, arg1, sizeOfArg2, and arg2.

Here, sizeOfArg1 is the size in bytes of arg1 and sizeOfArg2 is the size in bytes of arg2. arg1 and arg2 are void* pointers.

For single variables, I understand that you can use memcpy() or strlen() (if argument is a string). 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. The sendto() function accepts a void* buf argument.

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.

Any help would be appreciated.

Это было полезно?

Решение

Use a char buffer instead.

#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 с атрибуция
Не связан с StackOverflow
scroll top