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