【发布时间】:2011-09-21 00:07:11
【问题描述】:
在 Android 上使用动态加载 API(<dlfcn.h>:dlopen()、dlclose() 等)时遇到一些问题。
我正在使用 NDK 独立工具链(版本 8)来编译应用程序和库。
Android 版本为 2.2.1 Froyo。
这里是简单共享库的源代码。
#include <stdio.h>
int iii = 0;
int *ptr = NULL;
__attribute__((constructor))
static void init()
{
iii = 653;
}
__attribute__((destructor))
static void cleanup()
{
}
int aaa(int i)
{
printf("aaa %d\n", iii);
}
这是使用上述库的程序源代码。
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
void *handle;
typedef int (*func)(int);
func bbb;
printf("start...\n");
handle = dlopen("/data/testt/test.so", RTLD_LAZY);
if (!handle)
{
return 0;
}
bbb = (func)dlsym(handle, "aaa");
if (bbb == NULL)
{
return 0;
}
bbb(1);
dlclose(handle);
printf("exit...\n");
return 0;
}
有了这些源,一切正常,但是当我尝试使用一些 STL 函数或类时,程序会因分段错误而崩溃,当main()函数退出,例如,当将此源代码用于共享库时。
#include <iostream>
using namespace std;
int iii = 0;
int *ptr = NULL;
__attribute__((constructor))
static void init()
{
iii = 653;
}
__attribute__((destructor))
static void cleanup()
{
}
int aaa(int i)
{
cout << iii << endl;
}
使用此代码,程序在main() 函数退出之后或期间因分段错误而崩溃。
我尝试了几个测试,发现了以下结果。
- 不使用 STL 一切正常。
- 当使用 STL 并且最后不要调用
dlclose()时,一切正常。 - 我尝试使用
-fno-use-cxa-atexit或-fuse-cxa-atexit等各种编译标志进行编译,结果是一样的。
我使用 STL 的代码有什么问题?
【问题讨论】:
-
+1 格式良好的问题 ;)
-
so文件头中是否有STL头?你能把它带到cpp文件吗? (所以STL不会在接口中。)定义和声明是分开的吗?
-
我猜你说的是 aaa(...) 函数,如果是,那么声明和定义在不同的文件中。定义头文件为
#ifdef __cplusplus extern "C" #endif int aaa(int i); -
你的主程序也是C++,还是编译成C?
-
程序和库都是用C++编译器编译的。
标签: android c++ linux android-ndk