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

标签 java c++ jna

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

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

试试这个

关于java - 使用JNA在java中调用C++库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33514307/

相关文章:

java - 当我尝试通过我的应用程序发送电子邮件时遇到问题

java - 如何从本地拷贝文件分享给JCifs?

C++,实例化一个通用节点,使用模板存储一个对象的实例

java native loadlibrary 无法加载库 - Linux fedora25 java8

java - 在java中列出组合框中的对象

java - 检查标签是否为空的方法不起作用

c++ - Visual Studio 2015 错误 C4996 'std::_Copy_impl' : Function call with parameters that may be unsafe

C++。如何知道方法/变量的定义位置?或者如何询问编译器?

c# - 让 JNA 与 Java 一起工作 => C#?

android - 在 Android Studio 中设置 JNA