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

来源:互联网 发布:万科建筑设计优化微盘 编辑:程序博客网 时间:2024/05/08 08:40

于是自己模仿他的设计也写了个小程序,晒晒,关键就是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 __cplusplustypedef JNIEnv_ JNIEnv;#elsetypedef const struct JNINativeInterface_ *JNIEnv;#endifstruct 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 = &ge;#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;}


原创粉丝点击