简体   繁体   English

如何调用指向 function 指针的指针?

[英]How to call a pointer to a function pointer?

Normally, I'd call this function pointer using syntax like the following.通常,我会使用如下语法调用这个 function 指针。

using func_ptr = void (*)();

// ...

(*func_ptr)();

When wrapping a function pointer in a unique_ptr...将 function 指针包装在 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? ...如何调用指向 function 指针的指针? I tried...我试过了...

(**fp)();

to no avail.无济于事。

When wrapping a function pointer in a unique_ptr...将 function 指针包装在 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.请注意,在CC++函数的生命周期是不定式的,因此没有必要使用指向函数的智能指针。

Now since you are using dlsym so dynamic library are involved (this is outside of standard).现在,由于您使用的是dlsym ,因此涉及到动态库(这超出了标准)。 You may think: "yes my function has finite life time, since it is loaded from dll, so it is time for smart pointer".你可能会想:“是的,我的 function 的生命周期是有限的,因为它是从 dll 加载的,所以是时候使用智能指针了”。

Idea may seam good, but note that resource for management here is not aa function, but library itself.想法可能很好,但请注意,这里的管理资源不是 function,而是库本身。 You are openning dll by dlopen and close it with dlclose .您正在通过dlopen打开 dll 并使用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.这意味着指向 function 的智能指针仍然不是一个好的选择。

A proper solution is to use boost::dll (header only library), which does this for you in very nice way.一个适当的解决方案是使用boost::dll (仅标头库),它以非常好的方式为您做到这一点。

If you want do it your self you need:如果你想自己做,你需要:

  • class which will manage dll lifetime (load time) - may be managed by std::shared_ptr class 将管理 dll 生命周期(加载时间) - 可以由std::shared_ptr管理
  • classes which will represent functions in dll.将代表 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. 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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