0
void* l = dlsym(lib,"_ZN11Environment9LibLogger14log_processingEiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEjS6_z");
*(void **)&log_fcn   = l;
std::cout<<"Address"<<<<l<<"LOG_FCN "<<log_fcn<<std::endl;

I am trying to print address of l and log_fcn but both are not same. Why is that, and how can I get address of dlsym assign to function pointer?

Output example:

l= 0x7efe10eabaa0 LOG_FCN 1

void (*log_fcn)(int level, std::string frmt, unsigned int line_no, std::string file_name, ...); function decleration

4
  • @KonradRudolph void (*log_fcn)(int level, std::string frmt, unsigned int line_no, std::string file_name, ...); Commented May 10, 2022 at 10:06
  • 1
    (void*)log_fcn? the stream seems to convert it to bool instead of pointer otherwise Commented May 10, 2022 at 10:10
  • The compiler tries to convert log_fcn to something that can be printed, and because function pointers are not convertible to void*, the only valid match is bool Commented May 10, 2022 at 10:11
  • 1
    You should convert l to decltype(log_fcn), not assign to log_fcn through a void* lvalue. The latter is an aliasing violation. Commented May 10, 2022 at 10:13

1 Answer 1

3

There is an operator << for void*, but not for function pointers.
Function pointers are implicitly converted to bool, not void*, and bool prints as 0 or 1 by default.

Your 1 output indicates that log_fcn is not the null pointer.

Convert it when printing:

std::cout << "Address" << l << "LOG_FCN "<< reinterpret_cast<void*>(log_fcn) << std::endl;

I would recommend that you also do the assignment in the conventional form, by casting the right-hand side:

log_fcn = reinterpret_cast<decltype(log_fcn)>(l);
Sign up to request clarification or add additional context in comments.

4 Comments

The unnatural casting on the left side comes from the dlsym manual page. It states it’s the workaround for that in C99, casting void* to a function pointer is undefined.
This is C++, not C99.
Well, yes. In C++ rules are stricter. Don’t remember if there is any standard-conforming way in C++.
@numzero reinterpret_cast<decltype(log_fcn)>(l) and decltype(log_fcn)(l) are standard-conforming in C++, although conditionally-supported.

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.