0

A have callback function with this prototype:

void serverAnswer(void *pUserData, int flag);

I need to pass a buffer const uint8_t *buf to this function using the void parameter. How do i pass the buffer, and how can i access the elements of the buffer in the function?

Example (not working):

Call:

const uint8_t *buf;
int buf_len = 3;
serverAnswer(&buf, buf_len);

Access to buffer:

void serverAnswer(void *pUserData, int flag) {

uint8_t* p = (uint8_t *)pUserData;
uint8_t data = p[0];

}

2 Answers 2

0

&buf is a const uint8_t **. What you actually want to do is pass buf to serverAnswer, you'll need a const_cast to allow conversion from a const pointer to void*:

const uint8_t* buf;
serverAnswer(const_cast<uint8_t*>(buf), buf_len);

To avoid undefined behaviour you should put the const back in serverAnswer:

void serverAnswer(void *pUserData, int flag) {

const uint8_t* p = (const uint8_t *)pUserData;
uint8_t data = p[0];

}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply. I realized that my question was erraneous, i modified it. The task is not to pass the buffer, but the pointer to the buffer. See above.
same applies, you are still passing in a pointer to a pointer but casting it back to just a pointer
I if call serverAnswer(buf, buf_len) (without &) the compiler complains the call.
0

You're actually passing a pointer to the array during your call. In your code, what you're casting back to an uint8_t*, is an uint8_t**.

What you need to do, is either passing the array directly, or casting it to uint8_t** instead of uint8_t* and dereferencing it.

IMHO, passing the array directly is the best way to go, because passing a pointer to a pointer is not needed when you don't want to modify the pointed pointer, which seems to be your case

1 Comment

Welcome to Stack Overflow! I think this is a great answer, but maybe you could include an example of how to do what you're prescribing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.