JAVA访问C++动态库的2种方法

前段时间有朋友询问JAVA访问C++动态库的方法,应该是大家很关注的这些功能,下面说明。

如你有一个OutAdd.DLL的动态库,有一函数addTest(int a, int b)。java程序来调用

有2种方法,废话少说,直接代码说明。

1.最简单的是调用sun开发的com.sun.jna包来访问。

import com.sun.jna.Library;
import com.sun.jna.Native;

public class WithJNA {

 public interface OutAdd extends Library {
  OutAdd INSTANCE = (OutAdd) Native.loadLibrary("OutAdd",
    OutAdd.class);

  public int addTest(int a, int b);
 }

 public static void main(String[] arg) {
        System.out.println("java.lib:"+System.getProperty("java.library.path"));
  int c = OutAdd.INSTANCE.addTest(2345, 106);
  System.out.println("print:" + c);
 }

}

 

仅仅上面代码就OK了。

 

2采用最原始的JNI方式

java代码:

public class WithC {

 private static final String localPath = "C:/workspace/cxpWorkspace/JNIProject/src/";
 static{
  //myself dll loadLibrary也行,不过要配置环境变量
  System.load(localPath+"withjava.dll");
  //other dll
  System.load(localPath+"OutAdd.dll");
 }
 public static native int add(int a,int b);
 public static void  main(String[] arg){
  // use C++ dll
  int c=WithC.add(456, 802);
  System.out.println("out:"+c);
 }

}

 

withjava.DLL里面的代码

#include "stdafx.h"

#include "WithC.h"


typedef int (* MyType)(int,int);

JNIEXPORT jint JNICALL Java_WithC_add(JNIEnv *env, jclass jcl, jint a, jint b)
{

 MyType mytype;

 HINSTANCE dll_handle;

 dll_handle=LoadLibraryA("OutAdd.dll");

 int result =0;
 if(dll_handle != NULL){

 mytype=(MyType)GetProcAddress(dll_handle, "addTest");
    result = mytype(a,b);
 FreeLibrary(dll_handle);
 }
    return result;
}

 

withjava.DLL是一个来调用OutAdd.dll,需要自己写,用这个dll作为中转站调用OutAdd.dll,withjava.DLL的动态库引入了java命令行工具生成的头文件WithC.h。

 

OK,上面2个一样的结果,各有好处。

以上对第一次使用java调用dll的很有帮助,至少不用到处去找了,以上代码直接可用.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值