【问题标题】:JNA program function lookup failureJNA 程序函数查找失败
【发布时间】:2013-12-29 13:17:31
【问题描述】:

我是 JNA 编程新手,我要完成的任务是:

  1. C++ 库公开了将缓冲区“放入”文件并“查找”缓冲区的功能。我为这个库编译了一个共享对象(.so),头文件在“extern”C“”下提供了函数定义,使其对 C 编译器友好。

  2. 测试 java 程序以访问缓冲区。

代码如下所示:

C/C++ 代码:

extern "C"
{
int get(int length, char *buffer);
}

#include <iostream>
#include <string.h>

int get(int length, char *buffer)
{
    char *newBuff = new char[length];
    for (int i = 0; i < length; ++i)
    {
        newBuff[i] = 'a';
    }

    memcpy(newBuff, buffer, length);
    delete newBuffer;
    return length;
}

java代码:

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

public class TestJna
{
    public static interface TestNative extends Library
    {
        int get(int length, Memory buffer);
    }
    private static final TestNative lib_ = (TestNative)Native.loadLibrary("libsample.so", TestNative.class);
    public static void main(String[] args)
    {
        int length = 1024;
        Memory buffer = new Memory(length);
        int ret = lib_.get(length, buffer);
        System.out.println("ret:" + ret + ":buffer:" + buffer.toString());
    }
}

在运行程序时,我在调用“lib.get()”方法时收到以下错误消息:

线程“主”java.lang.UnsatisfiedLinkError 中的异常:查找函数“get”时出错:dlsym(0x7f8d08d1e7d0, get):找不到符号

【问题讨论】:

  • 我从未使用过 JNA,但它看起来像是在抱怨,因为您在 TestNative 接口内声明了一个名为 get 的函数,但从未定义它。
  • 您在delete newBuffer; 语句中错过了[],因为它是指向arrar 的指针。
  • 当然,但这不是主要问题,而 Java 代码保持不变。无论如何都会修复 C++ 中的内存泄漏
  • 使用nm filename 查看从库中导出了哪些符号。
  • nm 显示存在“get”符号 bash-3.2$ nm libsample.so 0000000000000eb0 T __Z3getiPc U __ZdaPv U __Znam U _memcpy U dyld_stub_binder bash-3.2$ c++filt __Z3getiPc get(int, char *)

标签: c++ jna


【解决方案1】:

您导出的符号(根据nm)已损坏。除了声明之外,您还需要在函数定义之前添加extern "C",即

extern "C" get(int length, char* buffer) {
    ...
}

您使用的第一个extern "C" 语法通常用于头文件中的声明组。您还必须明确地取消定义。

【讨论】:

    【解决方案2】:

    我可以通过如下修改代码使其工作:

    public static interface TestNative extends Library
        {
            int get(int length, Pointer buffer);
        }
    

    指针是通过以下方式获得的:

    Pointer bfPtr = Native.getDirectBufferPointer(buffer); // buffer points to ByteBuffer allocated as direct NIO buffer.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      相关资源
      最近更新 更多