一、用eclipse新建一个JAVA工程。
在Java工程中加入如下代码:
/*
* TestLibusb.java
*
* Created on: Nov 15, 2012
* Author: fx_swordsman
*/
package com.libusb;
public class TestLibusb {
static
{
System.loadLibrary("Jlibusb");
}
public native void test();
public static void main(String[] args) {
new TestLibusb().test();
}
}
二、生成JNI头文件:
在Java工程目录的src下执行如下:
javac com/libusb/TestLibusb.java
执行完后会生成TestLibusb.class文件,再执行如下:
javah -jni com.libusb.TestLibusb
即可生成com_libusb_TestLibusb.h头文件,内容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class com_libusb_TestLibusb */
#ifndef _Included_com_libusb_TestLibusb
#define _Included_com_libusb_TestLibusb
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_libusb_TestLibusb
* Method: test
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_libusb_TestLibusb_test
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
三、用C/C++实现com_libusb_TestLibusb.h文件中的函数,内容如下。
/*
* jni_libusb.c
*
* Created on: Nov 15, 2012
* Author: fx_swordsman
*/
#include
#include
#include "com_libusb_TestLibusb.h"
#include
static void print_devs(libusb_device **devs)
{
libusb_device *dev;
int i = 0;
while ((dev = devs[i++]) != NULL) {
struct libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(dev, &desc);
if (r < 0) {
fprintf(stderr, "failed to get device descriptor");
return;
}
printf("%04x:%04x (bus %d, device %d)\n",
desc.idVendor, desc.idProduct,
libusb_get_bus_number(dev), libusb_get_device_address(dev));
}
}
static int Jlsusb_print(void){
libusb_device **devs;
int r;
ssize_t cnt;
r = libusb_init(NULL);
if (r < 0)
return r;
cnt = libusb_get_device_list(NULL, &devs);
if (cnt < 0)
return (int) cnt;
print_devs(devs);
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return 0;
}
JNIEXPORT void JNICALL Java_com_libusb_TestLibusb_test
(JNIEnv *env, jobject obj)
{
printf("*************\n");
Jlsusb_print();
printf("*************\n");
return ;
}
四、编译上面写的 jni_libusb.c文件,生成共享库。
编译命令如下:
gcc -shared -fPIC -I /usr/lib/jvm/java-6-sun/include -I /usr/lib/jvm/java-6-sun/include/linux -I /usr/local/include/libusb-1.0 jni_libusb.c -lusb-1.0 -o libJlibusb.so
五、配置eclipse编译环境。
1、 将libJlibusb.so文件拷贝到eclipse的工程目录下。
2、右键java工程--->Run As ---> Run Configurations--->Arguments的VM arguments中加入如下内容:
-Djava.library.path=.
注:这表示你的生其的 libJlibusb.so库文件放在java工程根目录下。如不加会出现如下错误:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no Jlibusb in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1734)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1028)
at com.libusb.TestLibusb.(TestLibusb.java:7)
Could not find the main class: com.libusb.TestLibusb. Program will exit.
六、执行JAVA工程:
右键java工程--->Run As --->Java Application
在Console窗口中会输出如下(注:具体的USB设备VID/PID结果,不同的机会得到不同的结果):
*************
1d6b:0002 (bus 1, device 1)
1d6b:0002 (bus 2, device 1)
8087:0024 (bus 1, device 2)
8087:0024 (bus 2, device 2)
192f:0916 (bus 1, device 3)
*************
阅读(2110) | 评论(0) | 转发(0) |