您的位置:首页 > 编程语言 > C语言/C++

最近看了Java 调用C 和 C/C++反调Java,感叹当年的大牛为什么要这么弄

2011-09-05 16:00 861 查看
于是自己模仿他的设计也写了个小程序,晒晒,关键就是C++包裹了一个类 struct JNIEnv_ ,内部又通过组合的方式加入了const struct JNINativeInterface_ 的指针

佩服啊,还有那个this 我靠,要是我写我肯定想不到这么写, 我肯定这么写,当然我这么写必然看上去很垃圾。

return functions->GetVersion(&funcions)

但是这么写多不好看 由于类型的关系

我们不能这么写return functions->GetVersion(funcions) 而非得加个'&',可是大牛们一个this

return functions->GetVersion(this)

多简洁,又看不出破绽,佩服佩服。

#include <stdio.h>
#include <stdlib.h>

struct JNINativeInterface_;
struct JNIEnv_;

#ifdef __cplusplus
typedef JNIEnv_ JNIEnv;
#else
typedef const struct JNINativeInterface_ *JNIEnv;
#endif

struct JNINativeInterface_ {
int version;
int (*GetVersion)(JNIEnv *env);
};

struct JNIEnv_ {
const struct JNINativeInterface_ *functions;
#ifdef __cplusplus
int GetVersion() {
return functions->GetVersion(this);
}

#endif
};

int GetVersion(JNIEnv *env)
{
#ifdef __cplusplus
//JVM中代码不走这段,为运行方便而加
return env->functions->version;
#else
return (*env)->version;
#endif
}

struct JNINativeInterface_ g_env = {100, GetVersion};

void JNI_CreateJavaVM(void **penv)
{
#ifdef __cplusplus
//同上 JVM中不会走这个

(*(JNIEnv **)penv) = new JNIEnv;
(*(JNIEnv **)penv)->functions = &g_env;
#else
static JNIEnv ge = &g_env;
*(JNIEnv **)penv = ≥
#endif
}

void JNI_DestroyJavaVM(void **penv)
{
#ifdef __cplusplus
//同上 JVM不会走这个
delete (*(JNIEnv **)penv);
#else
#endif
*(JNIEnv **)penv = NULL;
}

int main(int argc, char **argv)
{
JNIEnv *env;
JNI_CreateJavaVM((void **)&env);
#ifdef __cplusplus
int v = env->GetVersion();
#else
int v = (*env)->GetVersion(env);
#endif
printf("version=%d\n", v);
JNI_DestroyJavaVM((void **)&env);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java c struct jvm jni