How does this make sense: * (void **) (& fptr) = dlsym (handle, "my_function"); `

The code comes from this page: http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html

Can you help me figure this out? It takes the address of the function pointer, discards it to void **, and then casts it. I do not know why this should work like this.

I appreciate your help! So far, the only advice I have received has been to "read it from right to left" or something like "read it in cycles from right to left."

+2
source share
3 answers

Code value:

  • Take the address fptr . The type of this expression is a pointer to a pointer to a function (of a specific type).
  • Put this pointer expression on "pointer to void pointer".
  • Separate the pointer to access the fptr object as if it were an object of type void * .
  • Assign the result of the right to the value of l obtained in step 3.

Unfortunately, the one who wrote this example in POSIX was on the crack because step 3 violates the C alias rules and thus causes undefined behavior. In particular, real-world compilers will optimize this code in ways that violate the intended use.

What the author of this example sought was to not discard the right-hand side from the pointer to void to the pointer to the function. This is based on the claim that the C standard requires this actor to generate a warning, but I carefully searched for this requirement and did not find such a requirement.

If such a problem really exists (warning requirement), then the only way to turn off the warning without causing undefined behavior (for example, a bad example in the POSIX text) is as follows:

 void (*fptr)(); // or whatever function pointer type you want void *temp = dlsym(handle, "my_function"); memcpy(&fptr, &temp, sizeof fptr); 
+10
source

The function returns a pointer to the function. This code says that I take a function pointer variable, giving me the address of this. Drop it to void ** . Now pass the value void ** and set the value void * = to the pointer that I received from the call.

+1
source

*(void **)(&fptr) = dlsym(handle, "my_function");

To make it easier

fptr is a pointer.

&fptr is the address of this pointer.

you attribute it

and then a link and assign the return value from the function.

0
source

Source: https://habr.com/ru/post/982557/


All Articles