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

22 篇文章 0 订阅
16 篇文章 0 订阅

于是自己模仿他的设计也写了个小程序,晒晒,关键就是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 = &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;
}


  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 22
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值