admin管理员组文章数量:1487745
多语言调用之 Java调用C/C++
Java 调用 C/C++ 1.创建一个类com.test.TestCall 内容如下 package com.test;
public class TestCall {
public native String getResponse(String request); }
2.编译得到TestCall.class文件 命令javah com.test.TestCall(如果不好使,前面执行一句set classpath=.) 得到com_test_TestCall.h文件,内容如下 /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_test_TestCall */
#ifndef _Included_com_test_TestCall #define _Included_com_test_TestCall #ifdef __cplusplus extern "C" { #endif /* * Class: com_test_TestCall * Method: getResponse * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_test_TestCall_getResponse (JNIEnv *, jobject, jstring);
#ifdef __cplusplus } #endif #endif
3.新建C/C++工程,引入com_test_TestCall.h头文件 TestCall.cpp #include "com_test_TestCall.h" JNIEXPORT jstring JNICALL Java_com_test_TestCall_getResponse (JNIEnv *pEnv, jobject obj, jstring jstr) { jstring response = pEnv->NewStringUTF("call C:"); jboolean isCpoy; const jchar *request = pEnv->GetStringChars(jstr,&isCpoy) ; //todo pEnv->ReleaseStringChars(jstr,request); return response; } 编译成TestCall.dll
4.将TestCall.dll放到eclipse工程下(或者运行参数java -Djava.library.path=“dll目录”) 完整TestCall.java package com.test;
public class TestCall { static { //dll名字 System.loadLibrary("TestCall"); }
public native String getResponse(String request); public static void main(String[] args) { TestCall call = new TestCall(); String message = call.getResponse("hello"); javax.swing.JOptionPane.showMessageDialog(null, message); } }
5.运行java,弹出对话框就算成功了。
当然现在有Java Native Access这个开源项目,方便了我们的调用。 JNA里面不需要按照com_test_XX这种格式定义头文件,只要定义一个方法接口,支持指针,非常好用。
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2024-10-11,如有侵权请联系 cloudcommunity@tencent 删除c++com编译接口java本文标签: 多语言调用之 Java调用CC
版权声明:本文标题:多语言调用之 Java调用CC++ 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/shuma/1754906061a3181108.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论