肚子饿了,先简单做下记录,吃饱了再来丰富..

为了方便编译生成so及binary,仍然在Eclipse+CDT+NDK环境中构建。
工程结构图如下:
project.structure

comparison.c将编译生成待加载的动态链接库libComparison.so,其代码如下:

1
2
3
4
5
6
7
8
#ifndef _Comparison_c
#define _Comparison_c

int max (int a, int b) {
return a > b? a : b;
}

#endif

Execute.c将编译生成可在Android中直接运行的可执行文件。其代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<stdio.h>
#include<dlfcn.h>

int main(void) {
// 必须写明绝对路径,否则找不着so文件呢
void *handle = dlopen("/data/local/libComparison.so",RTLD_LAZY);
int(*pfun)(int,int);
const char *error = NULL;

if(handle==NULL)
{
printf("error:dlopen libComparison.so Fail.\n");
return 1;
}

dlerror();
pfun = dlsym(handle,"max");
if((error=dlerror()) != NULL)
{
printf("error:dlsym method max fail.\n");
return 1;
}

printf("input tow number:\n");

int a, b;
scanf("%d%d", &a, &b);

int result = (*pfun)(a, b);

printf("Get:%d and %d, the max() return:%d\n",a, b, result);

dlclose(handle);

return 0;
}

Android.mk的作用在于声明配置并分别生成libComparison.so及Execute(binary)。其代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := Execute
LOCAL_SRC_FILES := Execute.c
#生成独立的可执行文件
include $(BUILD_EXECUTABLE)


include $(CLEAR_VARS)

LOCAL_MODULE := Comparison
LOCAL_SRC_FILES := comparison.c
#普通的so库
include $(BUILD_SHARED_LIBRARY)

右击工程 -> Build Project。则在libs下生成了libComparison.so及Execute(binary)。
使用ADB命令将这两个文件push到手机。并执行操作查看效果如下图:
dlopen.result