最近遇到一个需求是用户提交一份c++的代码,然后要用java去调用户的方法并且给返回值。
这周搞这个东西搞了一个周,然后也是没太搞明白,争取下周能实现对于std::map、set之类的调用。
目前的系统是macos,其实跟linux都一样,就是.so变成.dylib了。
https://blog.csdn.net/boling_cavalry/article/details/118636417
这个讲的挺不错的,如果需要web服务的话,各种package的层次挺恶心人的。
首先是我的一个层次图
这个是我从spring官网随手下的一个web框架,然后又跟javacpp整合了一下。
几个坑:
javacpp.jar放在java下面,
.h和native类俩放在一起,
这里我没有正规的分包,理论上分包是不影响的,毕竟调的是NativeLibrary的实例
然后是代码
NativeLibrary.h
#include<vector>
namespace NativeLibrary {
class NativeClass {
public:
int add(int a, int b){
return a+b;
};
int sum(std::vector<int>& v){
int p=0;
std::sort(v.begin(),v.end());
for(auto x:v)
p+=x;//p+=x;
return p;
}
};
}
NativeLibrary .java
package com.example.restservice;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
@Platform(include= "NativeLibrary.h",compiler = "cpp11")
@Namespace("NativeLibrary")
public class NativeLibrary {
public static class NativeClass extends Pointer {
static { Loader.load(); }
public NativeClass() { allocate(); }
private native void allocate();
public native int add(int a, int b);
public native int sum(@StdVector int[] pasd);
}
}
Controller
package com.example.restservice;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
@GetMapping("/add")
public int add(@RequestParam(value = "a") int a,@RequestParam(value = "b") int b){
NativeLibrary.NativeClass l = new NativeLibrary.NativeClass();
return l.add(a,b);
}
@GetMapping("/sum")
public int sum(){
int a[] = new int[20];
a[4]=10;
a[5]=20;
NativeLibrary.NativeClass l = new NativeLibrary.NativeClass();
return l.sum(a);
}
}
在java目录下执行这两个命令,就会生成.dylib动态库文件,然后启动web服务即可
javac -cp javacpp.jar com/example/restservice/NativeLibrary.java
java -jar javacpp.jar com/example/restservice/NativeLibrary.java
第一次用csdn写blog.. 确实挺丑的