Mapping const char** to Java type with JNA

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I am trying to use a C++ library in Java with JNA. In the header file of the library I have the following method declaration:

extern "C" void foo(const char** bar); 

The paramterer bar should be passed to foo empty, and foo vill assign it a value that I want to retreive in Java. How should the corresponding Java method declaration be set up (e.g. what Java type should I map bar to), and how can I use it?

I have tried the following Java declarations:

void foo(String bar); void foo(String[] bar); void foo(Pointer bar); 

They all result in the following error when I call foo:

Exception in thread "main" java.lang.Error: Invalid memory access

回答1:

Find below a small snippet.

libfoo.cpp

#include <stdio.h> extern "C" void foo(const char** bar);  void foo(const char** bar) {     for (int i = 0; bar[i] != '\0'; i++) {         fprintf(stdout, "%s\n", bar[i]);     } } 

LibFooDemo.java

import com.sun.jna.Library; import com.sun.jna.Native;  public class LibFooDemo {      public interface FooLibrary extends Library {         FooLibrary INSTANCE = (FooLibrary)                 Native.loadLibrary("foo", FooLibrary.class);         void foo(String[] format);     }      public static void main(String[] args) {         String[] vals = {"foo", "bar", "foobar"};         FooLibrary.INSTANCE.foo(vals);     } } 

compile all sources

gcc -c -fPIC libfoo.cpp -o libfoo.o gcc -shared -o libfoo.so  libfoo.o javac -cp jna-4.2.1.jar LibFooDemo.java 

run the Java program

java -Djava.library.path=. -cp jna-4.2.1.jar:. LibFooDemo 

output

foo bar foobar 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!