用java编译c代码 java代码如何编译( 二 )


view plain #!/bin/sh # Define some constants ONSSERVER=ONSServer PROJECT_PATH=/root/iot oid JAR_PATH=$PROJECT_PATH/lib BIN_PATH=$PROJECT_PATH/bin SRC_PATH=$PROJECT_PATH/src/$ONSSERVER
# First remove the sources list file if it exists and then create the sources file of the project rm f $SRC_PATH/sources find $SRC_PATH/ name * java$SRC_PATH/sources list
# First remove the ONSServer directory if it exists and then create the bin directory of ONSServer rm rf $BIN_PATH/$ONSSERVER mkdir $BIN_PATH/$ONSSERVER
# Compile the project javac d $BIN_PATH/$ONSSERVER classpath $JAR_PATH/jdom jar $JAR_PATH/oro jar @$SRC_PATH/sources list下面是文件run 用于执行程序 view plain #!/bin/sh
# Define some constants ONSSERVER=ONSServer PROJECT_PATH=/root/iot oid JAR_PATH=$PROJECT_PATH/lib BIN_PATH=$PROJECT_PATH/bin
lishixinzhi/Article/program/Java/hx/201311/27024
写一段java代码,调用c程序 , 都有什么办法JAVA以其跨平台的特性深受人们喜爱 , 而又正由于它的跨平台的目的,使得它和本地机器的各种内部联系变得很少,约束了它的功能 。解决JAVA对本地操作的一种方法就是JNI 。
JAVA通过JNI调用本地方法,而本地方法是以库文件的形式存放的(在WINDOWS平台上是DLL文件形式,在UNIX机器上是SO文件形式) 。通过调用本地的库文件的内部方法,使JAVA可以实现和本地机器的紧密联系,调用系统级的各接口方法 。
简单介绍及应用如下:
一、JAVA中所需要做的工作
在JAVA程序中,首先需要在类中声明所调用的库名称,如下:
static
{
System.loadLibrary(“goodluck”);
}
在这里 , 库的扩展名字可以不用写出来,究竟是DLL还是SO,由系统自己判断 。
还需要对将要调用的方法做本地声明,关键字为native 。并且只需要声明,而不需要具体实现 。如下:
public
native
static
void
set(int
i);
public
native
【用java编译c代码 java代码如何编译】static
int
get();
然后编译该JAVA程序文件,生成CLASS , 再用JAVAH命令 , JNI就会生成C/C++的头文件 。
例如程序testdll.java,内容为:
public
class
testdll
{
static
{
System.loadLibrary("goodluck");
}
public
native
static
int
get();
public
native
static
void
set(int
i);
public
static
void
main(String[]
args)
{
testdll
test
=
new
testdll();
test.set(10);
System.out.println(test.get());
}
}
用javac
testdll.java编译它,会生成testdll.class 。
再用javah
testdll , 则会在当前目录下生成testdll.h文件,这个文件需要被C/C++程序调用来生成所需的库文件 。
二、C/C++中所需要做的工作
对于已生成的.h头文件,C/C++所需要做的,就是把它的各个方法具体的实现 。然后编译连接成库文件即可 。再把库文件拷贝到JAVA程序的路径下面 , 就可以用JAVA调用C/C++所实现的功能了 。
接上例子 。我们先看一下testdll.h文件的内容:
/*
DO
NOT
EDIT
THIS
FILE
-
it
is
machine
generated
*/
#include
jni.h
/*
Header
for
class
testdll
*/
#ifndef
_Included_testdll
#define
_Included_testdll
#ifdef
__cplusplus
extern
"C"
{
#endif
/*
*
Class:
testdll
*
Method:
get
*
Signature:
()I
*/
JNIEXPORT

推荐阅读