共享对象可以访问加载它的应用程序的内存吗?

huangapple go评论62阅读模式
英文:

Can shared object access memory of app that loaded it?

问题

我是新手共享库(Qt5/C++/Linux)。我成功创建了一个应用程序,可以加载许多.so文件中的一个(每个动物一个文件:dog.so、cat.so、mouse.so)。到目前为止一切都很顺利。

我假设共享库中的方法可以调用应用程序中的方法(例如:dog.so可以调用app::soundPlayerInstance(),该方法获取应用程序中SoundPlayer单例的指针)。

尽管我的代码编译正常,但当我运行代码时,似乎我得到的SoundPlayer实例是一个新的实例(另一个单例被创建)。

我怀疑我对.so文件能够做什么有所困惑。.so文件能否访问加载它的应用程序,以调用方法、访问全局变量等?

如果不能,如果应用程序将对象地址传递给.so构造函数,那么是否可以?还是有更好的方法可以实现这一点?或者共享对象真的只是一个单向(应用程序调用.so)的概念吗?


更新:我的单例模板如下。(请不要就单例进行辩论,仅供参考)

// 创建或返回派生类的实例
static T* instance() {

// 如果尚未有实例,则创建一个
s_mutex.lock();
bool runPostConstructor = (s_instance == nullptr);
if (s_instance == nullptr) s_instance = new T;
s_mutex.unlock();

}

英文:

I am new to shared libraries (Qt5/C++/Linux). I managed to create an app which can load one of many .so files (one per animal: dog.so, cat.so, mouse.so). So far works great.

I assumed that methods in the shared libraries could call methods in the app (eg: dog.so can call app::soundPlayerInstance() which gets a pointer to the SoundPlayer singleton in the app).

Although my code compiled fine, when I run the code it appears that the instance of SoundPlayer I'm getting is a NEW one. (Another singleton created).

I suspect I am confused about what a .so can do. Can an .so reach into the app that loaded it, to call methods, access global vars, etc?

If not, if the app passed object addresses into .so constructor, could it then? Or is there a better way to do this? Or is a shared object really a one way only (app call so) concept?


Update: My singleton template is below. (Please don't get into debate about Singletons, just provided for reference)

// Create or return the instance if the derived class
static T* instance() {

    // If no instance yet, the create one
    s_mutex.lock();
    bool runPostConstructor = (s_instance == nullptr);
    if (s_instance == nullptr) s_instance = new T;
    s_mutex.unlock();
}

答案1

得分: 0

是的,如果它知道这些对象的地址。共享库与应用程序无关。应用程序链接到库,因此它知道如何定位函数。然而,将回调函数或对象从应用程序传递给库非常常见。这样,库就有了一个地址,可以调用应用程序中的函数。

英文:

Yes, if it knows the address of such objects. A shared library is not linked to the application. The application is linked to the library, so it knows how to locate functions. It is however very common to pass callback functions or objects from the application to the library. That way the library has an address, so it can call a function in the application.

huangapple
  • 本文由 发表于 2023年2月27日 07:29:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定