简体   繁体   中英

How to call a pointer to a function pointer?

Normally, I'd call this function pointer using syntax like the following.

using func_ptr = void (*)();

// ...

(*func_ptr)();

When wrapping a function pointer in a unique_ptr...

std::unique_ptr<func_ptr> fp;

fp = std::make_unique<func_ptr>((func_ptr) dlsym(handle, "somefunc"));

... how does one call a pointer to a function pointer? I tried...

(**fp)();

to no avail.

When wrapping a function pointer in a unique_ptr...

This is a problem, since this doesn't have sense. Smart pointers are for things which have finite well defined lifetime. Things which you can create and destroy. Note that in C and C++ functions have infinitive life time, ergo there is no point to use smart pointers to functions.

Now since you are using dlsym so dynamic library are involved (this is outside of standard). You may think: "yes my function has finite life time, since it is loaded from dll, so it is time for smart pointer".

Idea may seam good, but note that resource for management here is not aa function, but library itself. You are openning dll by dlopen and close it with dlclose . So the handle to library should be managed by smart pointer. This means that smart pointer to function still is not a good choice.

A proper solution is to use boost::dll (header only library), which does this for you in very nice way.

If you want do it your self you need:

  • class which will manage dll lifetime (load time) - may be managed by std::shared_ptr
  • classes which will represent functions in dll. They may hold shared_ptr to dll class, to ensure that dll is loaded as long as there is any class holding pointer to function in that dll.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM