请考虑以下代码示例。我的问题是:Foo :: bar存储在内存中的什么位置?它存储在main.cpp编译到的程序的静态存储中吗?如果是这样,则卸载myDll.so会发生什么?
//myDll.hpp
//class definitions
class Bar
{
public:
Bar() = default;
};
class Foo
{
public:
static Bar bar;
};
//declaring free function to be exported
extern "C" Bar* getBar();
//myDll.cpp
#include "myDll.hpp"
//initializing static member variable
Bar Foo::bar;
//definition of exported function
Bar* getBar()
{
return &(Foo::bar);
}
假设将myDll.cpp制成myDll.so,如下所示:g++ -shared -fPIC -o myDll.so myDll.cpp
,并像这样动态加载:
//main.cpp
void* handle = dlopen( "/path/to/dll/myDll.so", RTLD_NOW);
// do stuff with handle...
dlclose( handle );
调用dlclose()会发生什么? Foo :: bar是否会立即超出范围?
是。 Foo::bar
存在于myDll.so
的静态存储部分(“ .data”段)中,在dlclose
之后将被取消映射。
我可以想到两个例外:
dlclose()
,尽管依靠它可能是不明智的。dlopen
,则第一次调用dlopen
不会卸载该库。