繁体   English   中英

使用JNA在java中调用C ++库

[英]Calling C++ library in java using JNA

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

#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 ++中使用这个库并调用它的函数。

#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示例中使用它。

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));
    }
}

现在这个程序遇到下面给出的错误:

/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));
}
}

试试这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM