linux java 运行c 程序设计_Java语言深入学习之Java调用C/C++的过程

我的项目比较复杂,需要调用动态链接库,这样在JNI传送参数到C程序时,需要对参数进行处理转换。才可以被C程序识别。

大体程序如下:

public class SendSMS {

static

{

System.out.println(System.getProperty("Java.library.path"));

System.loadLibrary("sms");

}

public native static int SmsInit();

public native static int SmsSend(byte[] mobileNo, byte[] smContent);

}

在这里要注意的是,path里一定要包含类库的路径,否则在程序运行时会抛出异常:

java.lang.UnsatisfiedLinkError: no sms in java.library.path

at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1491)

at java.lang.Runtime.loadLibrary0(Runtime.java:788)

at java.lang.System.loadLibrary(System.java:834)

at com.mobilesoft.sms.mobilesoftinfo.SendSMS.(SendSMS.java:14)

at com.mobilesoft.sms.mobilesoftinfo.test.main(test.java:18)

Exception in thread "main"

指引的路径应该到.dll文件的上一级,如果指到.dll,则会报:

java.lang.UnsatisfiedLinkError: C:\sms.dll: Can’t find dependent libraries

at java.lang.ClassLoader$NativeLibrary.load(Native Method)

at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1560)

at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1485)

at java.lang.Runtime.loadLibrary0(Runtime.java:788)

at java.lang.System.loadLibrary(System.java:834)

at com.mobilesoft.sms.mobilesoftinfo.test.main(test.java:18)

Exception in thread "main"

通过编译,生成com_mobilesoft_sms_mobilesoftinfo_SendSMS.h头文件。(建议使用Jbuilder进行编译,操作比较简单!)这个头文件就是Java和C之间的纽带。要特别注意的是方法中传递的参数jbyteArray,这在接下来的过程中会重点介绍。

/* DO NOT EDIT THIS FILE - it is machine generated */

#include

/* Header for class com_mobilesoft_sms_mobilesoftinfo_SendSMS */

#ifndef _Included_com_mobilesoft_sms_mobilesoftinfo_SendSMS

#define _Included_com_mobilesoft_sms_mobilesoftinfo_SendSMS

#ifdef __cplusplus

extern "C" {

#endif

/*

* Class: com_mobilesoft_sms_mobilesoftinfo_SendSMS

* Method: SmsInit

* Signature: ()I

*/

JNIEXPORT jint JNICALL Java_com_mobilesoft_sms_mobilesoftinfo_SendSMS_SmsInit

(JNIEnv *, jclass);

/*

* Class: com_mobilesoft_sms_mobilesoftinfo_SendSMS

* Method: SmsSend

* Signature: ([B[B)I

*/

JNIEXPORT jint JNICALL Java_com_mobilesoft_sms_mobilesoftinfo_SendSMS_SmsSend

(JNIEnv *, jclass, jbyteArray, jbyteArray);

#ifdef __cplusplus

}

#endif

#endif0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值