JAVACPP整合web服务小demo

最近遇到一个需求是用户提交一份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.. 确实挺丑的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值