static int write_stream(const void *buffer, size_t size, void *app_key)
{
char *stream = (char *)app_key;
return 0;
}
Why pointer casting does
not result in a copying of (size_t size) bytes from buffer into the
stream defined by app_key?
Thanks
Edit: I’m calling this function as argument of another function to use callback :
static int write_stream(const void *buffer, size_t size, void *app_key)
{
char *stream = (char *)app_key;
return 0;
}
int print_to_2buf(char *ostream, struct asn_TYPE_descriptor_s *td, void *struct_ptr)
{
asn_enc_rval_t er; /* Encoder return value */
// write_stream is called as argument
er = xer_encode
(
td,
struct_ptr,
XER_F_BASIC,
/* BASIC-XER or CANONICAL-XER */ write_stream,
ostream
);
return (er.encoded == -1) ? -1 : 0;
}
From your question, I can’t be certain your level of understanding, but it looks as though you are not familiar with the mechanics of pointers, so I will try to give a quick explanation.
Your parameter void *app_key is an integer that stores the location in memory of a block of unknown (void) type.
Your char *stream is also an integer, it stores the location in memory of a block of char type (either a single char or the first char in a continuous block).
Your line of code
char *stream = (char *)app_keycopies the integer value of app_key (that is, the address in memory that app_key refers to), and stores it also in stream.At this point, both app_key and stream store the same location in memory — the address of the first character in your app_key (assuming that a string was passed as the parameter).
Realize, however, that the only thing that was copied was the integer memory address of your app_key. There is still only one copy.
What it sounds like you wanted to do was to make an entire new copy of the app_key string, one that was stored in a different location in memory (perhaps so that when the function returns and the original string is destroyed you still have your copy).
In order to do that, you need to do the following:
There are many ways to do this depending on what your needs are. Here is one:
Because you are working with strings, you could also make use of the strcpy() function (potentially paired with strlen). Those functions all assume that you are using a NULL-terminated string (that is, the string is a sequence of
chars, with a final\0at the end to indicate the end.