最近看了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)
多简洁,又看不出破绽,佩服佩服。
佩服啊,还有那个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/c++低?为什么用jni调用效率高?
- 【C++&Java】构造函数的调用点
- JNI编程—— 让C++和Java相互调用
- AndroidJNI 通过C++调用JAVA
- Java调用C++和C++调用Java的方法
- android jni C++ java 相互调用
- JNI编程-让C++和Java相互调用
- cocos2d-x 中多线程的c/c++代码通过JNI调用java代码
- java使用jnative jar包调用C/C++
- java中如何使用JNI调用C++写的函数
- swig--在java、C#中调用c++写的DLL(以vs2012配置为例)
- Java调用C++ API完整示例(dll)
- NDK开发之c++调用java
- 为什么Java可以跨平台c/c++不可以吗
- 图解安卓-c++开发-通过java 调用c++ jni的使用
- java 调用c/c++
- Android-NDK开发之基础--Android JNI实例代码(一)-- 在JNI中执行Java方法--C/C++调用Java
- 【转载整理】eclipse 开发c/c++、Java使用JNI调用C程序、生成64位dll动态链接库
- 【转】使用JNI进行混合编程:在C/C++中调用Java代码
- Java调用C/C++编写的第三方dll动态链接库(非native API)--- JNI