遇到java调用共享内存的问题,
java似乎没找到调用共享内存的的api
如果是调用“内存”,去看http://haoningabc.iteye.com/blog/1329079
只能用webservce或jni的方式去java调用c了
为了不把性能消耗在在网络传输上,让webservice先滚蛋
用jna吧,c调用共享内存的就不说了,《linux网络编程第二卷》很详细
jni不好用,还是jna简单
如果在windows下
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class HelloWorld {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
void printf(String format, Object... args);
}
public static void main(String[] args) {
CLibrary.INSTANCE.printf("in windows\n");
for (int i = 0; i < args.length; i++) {
CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
}
}
}
如果在linux下
顺便把c复习一下,准备做一个testadd的动态库,先测一下动态库是否好使,
先写3个文件test.h test.c testadd.c
test.h
#include <stdio.h>
void add();
test.c
#include <stdio.h>
#include "test.h"
int main()
{
printf("haha\n");
add();
}
testadd.c
#include <stdio.h>
#include <unistd.h>
void add()
{
char name[65];
printf("this is add \n");
gethostname(name, sizeof(name));
printf("hostname=%s\n",name);
system("ls");
}
生成libtestadd.so
测试一下是否好使
[root@redhat5 c]# gcc -fpic -shared -o libtestadd.so testadd.c
[root@redhat5 c]# gcc -o test test.c -I. -L. -ltestadd
[root@redhat5 c]# ./test
(有写系统可能会报错,比如fedora16,如果报./test: error while loading shared libraries: libtestadd.so: cannot open shared object file: No such file or directory,需要设置一下 export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:当前跑程序的目录就可以了)
haha
this is add
hostname=122226
a.out libtestadd.so TestAddService.class test.h
biji.txt main.c TestAddService.java y.tab.c
JNA.chm test TestAddService$TestAdd.class
jna.jar testadd.c test.c
[root@redhat5 c]#
yeh,"this is add"是libtestadd.so打印的,
现在用jna调用libtestadd.so
把jna.jar放到这个目录下
编写TestAddService.java
import com.sun.jna.Library;
import com.sun.jna.Native;
public class TestAddService {
public TestAddService() {
}
public interface TestAdd extends Library {
TestAdd INSTANCE = (TestAdd) Native.loadLibrary("testadd",TestAdd.class);
public void add();
}
public static void main(String[] args) {
TestAdd.INSTANCE.add();
System.out.println("哦 yeh yeh jna in linux");
}
}
[root@redhat5 c]# javac -cp .:jna.jar TestAddService.java
[root@redhat5 c]# java -cp .:jna.jar TestAddService
this is add
hostname=122226
a.out libtestadd.so TestAddService.class test.h
biji.txt main.c TestAddService.java y.tab.c
JNA.chm test TestAddService$TestAdd.class
jna.jar testadd.c test.c
哦 yeh yeh jna in linux
完了,java定义一个c接口就完了