使用JNA在Java中调用C ++库 [英] Calling C++ library in java using JNA

查看:114
本文介绍了使用JNA在Java中调用C ++库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为下面给出的函数创建了一个c ++库

I have created a c++ lib for function given below

#include "Test.h" 
#include "iostream"      
extern "C" int add(int x,int y) {    
Add instance;
return instance.add(x,y);  
}
Add::Add()
{
std::cout<<"In Add Constructor::"<<std::endl;
}   
int Add::add(int x,int y) {
return x+y;  
}

然后我在另一个C ++中使用了这个库,并调用了它的函数.

then i used this library in another c++ and call its function.

#include "Test1.h"
#include "iostream"
Test1::Test1()
{
std::cout<<"InConstructor of Test1 Library::"<<std::endl;
int result = 0;
result = CallingLibFunction(10,20);
std::cout<<"SUM RESULT : "<<result<<std::endl;
}
extern "C" int CallingLibFunction(int x,int y) {

Test1 instance;
return instance.CallingLibFunction(x,y); 
} 
int Test1::CallingLibFunction(int x, int y)
{
int value = addFunc.add(x,y);
return value;
}

现在我已经为Test1创建了新的库.然后在Java的jna示例中使用它.

now i have created new library for Test1. and then use it in my jna example in java.

import com.sun.jna.Library;
import com.sun.jna.Native;
public class Test {
    static{
        System.setProperty("java.library.path", "/root/Desktop/Pragati/OSGI/JNA/JNAExample/JNASimpleExample/JNAApp/bin");
        System.out.println("java lib path : " + System.getProperty("java.library.path"));
        //System.loadLibrary("src");            
    }

    public interface Test1 extends Library
    {
        Test1 INSTANCE = (Test1) Native.loadLibrary("Test1", Test1.class);
        int CallingLibFunction(int x, int y);
    }
    //CallingLibFunction
    public static void main(String[] args) {

        Test1 lib = Test1.INSTANCE;
        System.out.println(lib.CallingLibFunction(10, 20));
    }
}

现在此程序遇到以下错误:

now this program encounter error that is given below:

/usr/java/jdk1.8.0_25/bin/java: symbol lookup error: /root/Desktop/Pragati/OSGI/JNA/JNAExample/JNASimpleExample/JNAApp/bin/libTest1.so: undefined symbol: _ZN3AddC1Ev

推荐答案

import com.sun.jna.Library;
import com.sun.jna.Native;
public class Test {
    static    {
    System.setProperty("java.library.path", "/root/Desktop/Pragati/OSGI/JNA/JNAExample/JNASimpleExample/JNAApp/bin");
    System.out.println("java lib path : " + System.getProperty("java.library.path"));
    //System.loadLibrary("src");            
}

public interface Test1 extends Library
{
   // Loading Referenced Libraries first
 Add ADD_INSTANCE = (Add) Native.loadLibrary("Add", Test.class);


    Test1 INSTANCE = (Test1) Native.loadLibrary("Test1", Test1.class);
    int CallingLibFunction(int x, int y);
}
//CallingLibFunction
public static void main(String[] args) {

    Test1 lib = Test1.INSTANCE;
    System.out.println(lib.CallingLibFunction(10, 20));
}
}

尝试一下

这篇关于使用JNA在Java中调用C ++库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆