java 調用linux C++生成的so文件

TestHello.h

#pragma once

#include <cstdio>
#include<stdio.h>
extern "C" {
    extern int test1(int a, int b);
}

class TestHello
{
public:
    TestHello();

    static void test();
    static int addTest(int a, int b);
};

TestHello.cpp:

#include "TestHello.h"

TestHello::TestHello()
{
    
}

void TestHello::test()
{
    printf("helloworld to java!\n");
}

int TestHello::addTest(int a, int b)
{
    return (a + b);
}

int test1(int a, int b)
{
    return (a + b);
};

 

c_wrapper.cpp
#include "TestHello.h"

#define DLL_EXPORT


extern "C" DLL_EXPORT TestHello *TestHello_ctor();

TestHello *TestHello_ctor()
{
    return new TestHello();
}

extern "C" DLL_EXPORT void TestHello_test(const TestHello *self)
{
    return self->test();
}

extern "C" DLL_EXPORT void TestHello_addTest(TestHello *self, int a, int b)
{
    self->addTest(a, b);
}

 

TestHello.java
//import java.lang.annotation.Native;

/**
 * @author xxx
 * @date 2020/6/9 19:54
 */
//public class TestC {
//}

package com.navinfo.jna.test;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

public class TestHello {
    //繼承Library,用於加載庫文件 --Class mapping
    public interface CLibrary extends Library {
        // 加載libhello.so鏈接庫
        public String JNA_ImgProcess = "HelloToJava";
        public CLibrary instance = (CLibrary) Native.loadLibrary(CLibrary.JNA_ImgProcess, CLibrary.class);

        // 此方法爲鏈接庫中的方法  function mapping
        int test1(int a, int b);

        Pointer TestHello_ctor();

        void TestHello_test(Pointer self);

        int TestHello_addTest(Pointer self, int a, int b);

    };

    private Pointer self;

    public TestHello()
    {
        self = CLibrary.instance.TestHello_ctor();
    }

    int test1(int a, int b)
    {
       return  CLibrary.instance.test1(a, b);
    }

    void test()
    {
        CLibrary.instance.TestHello_test(self);
    }

    int addTest(int a, int b)
    {
        return CLibrary.instance.TestHello_addTest(self, a, b);
    }

};
My_Main.java
/**
 * @author xxx
 * @date 2020/6/10 14:28
 */

//package main.java;
//import  main.java.TestC;

package com.navinfo.jna.test;

import  com.navinfo.jna.test.TestHello;
import com.navinfo.jna.test.TestHello.CLibrary;

public class My_Main {

    //調用,singleton
    public static void main(String[] args) {
        System.out.println("hello zst");

        TestHello instance = new TestHello();
        instance.test();
        int c0 = instance.test1(10, 20);
        int c1 = instance.addTest(10, 20);

        System.out.println("c0:" + c0 );
        System.out.println("c1:" + c1 );

    }
}

如果java帶包名:

編譯:

javac -classpath jna-5.5.0.jar *.java -d .

運行:

java -classpath .:jna-5.5.0.jar com.navinfo.jna.test.My_Main

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章