Java调用C++的DLL设计!!!解耦实用!!!

本文介绍了Java通过JNI调用C++的问题,提出使用Python作为中间桥梁的解决方案,避免频繁修改Java代码。通过Python调用Python和C++,并将方法元数据存储在注册中心,方便扩展方法时仅更新元数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题背景:Java调用C++,通常推荐用JNI(Java Native Interface)http://t.csdnimg.cn/kjOND

但是调用时每调用一个C++方法都需要在Java程序中增加,不符合设计时的开放封闭原则,业务一边程序就要修改

public class CallCPlus extends CallImp {
    @Override
    public void execute() {

    }
    public native void test(String url);
    static {
        System.load("C:\\Users\\111\\Desktop\\flowable\\ruoyi-flowable-plus-0.8.X\\ruoyi-flowable-plus-0.8.X\\ruoyi-flowable\\src\\main\\java\\com\\ruoyi\\flowable\\external\\CPlus\\Call.dll");
    }
}

1.Java调用Python

public void callpython(String interpreter, String py_url, String args,String methodName,String returnType){

        Process proc;
        String[] cmds = new String[]{interpreter, py_url,args,methodName,returnType};
        try {
            proc = Runtime.getRuntime().exec(cmds);// 执行py文件
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

2.Python调用C++ 

def callCPlus(methodName,args,returnType,source):
    pDll = CDLL(source)

    # 获取解析的参数
    Arr=parseArgs(args)

    # 获取指定方法名的函数指针
    myfun = getattr(pDll, methodName)

    #参数类型
    myfun.argtypes = Arr[1]

    # 返回值类型
    myfun.restype = parseReturn(returnType)

    #调用 C++ 函数,将参数值解压出来,类似于js中的...

    result=myfun(*Arr[0])

    print(result)

注明:方法名、参数、返回值和dll路径这些函数元数据存放至注册中心(数据库)中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GISer_Jinger

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值