我有问题让JNA全部解决了。我试图调用一个函数,该函数作为参数指向函数和const char*
。我的C代码看起来像这样:
typedef void (*example_ptr)(const char*);
void exampleMethod(const char* value)
{
printf("This is the string: %s\n", value);
}
void example_triggerCallback(const example_ptr func, const char* str) {
printf("provided str: %s", str);
func(str);
}
为了实现这一目标,我用Java编写了这样的JNA包装器
public class Main {
public interface TestLibrary extends Library {
TestLibrary INSTANCE = (TestLibrary)
Native.loadLibrary("libtest",
TestLibrary.class);
interface ExampleCallback extends Callback {
void invoke(String str);
}
class ExampleCallbackImpl implements ExampleCallback {
public void invoke(String str) {
System.out.println("example: " + str);
}
}
void example_triggerCallback(ExampleCallback callback, String str);
}
public static void main(String[] args) {
TestLibrary testLibrary = TestLibrary.INSTANCE;
final TestLibrary.ExampleCallbackImpl callback = new TestLibrary.ExampleCallbackImpl();
testLibrary.example_triggerCallback(callback, "testiddy test test");
}
}
我面临的问题是C代码中的printf
中的example_triggerCallback
实际上是被调用的,我在Java控制台上得到了输出但是我真正想要实现的是我想从Java端传递指针来自C的exampleMethod
所以它将打印通过的String
。现在func(str)
似乎被忽略了。我在这里错过了什么?
基于found in JNA documentation的东西:
typedef void (*ExampleCallback)(const char*);
void exampleMethod(const char* value)
{
printf("This is the string: %s\n", value);
}
void example_triggerCallback(const example_ptr func, const char* str) {
printf("provided str: %s", str);
func(str);
}
public interface CLibrary extends Library {
// define an interface that wraps the callback code
public interface ExampleCallbackInterface extends Callback {
void invoke(String val);
}
// functions available in library (name must match)
public void exampleMethod(String value);
public void example_triggerCallback(ExampleCallbackInterface callback);
}
// define an implementation of the callback interface
public static class CallbackExample implements Example22CallbackInterface {
private CLibrary lib;
public CallbackExample(CLibrary useLib) {
lib = useLib;
}
@Override
public void invoke(String val) {
lib.exampleMethod(val);
}
}
...
final CLibrary clib = (CLibrary)Native.loadLibrary("testlib", CLibrary.class);
...
// instantiate a callback wrapper instance
final CallbackExample callback = new CallbackExample(clib);
// pass the callback wrapper to the C library
clib.example_triggerCallback(callback);
由于我在其他一些网站上回答了这个问题,我知道它适用于提问者。
我不太了解JNA但是如果我不得不假设,传递一个Java字符串“testiddy test test”可能与将字符指针传递给C可能不一样。你能尝试改变你的:void example_triggerCallback(ExampleCallback callback, String str);
致:void example_triggerCallback(ExampleCallback callback, char[] str);
看看是否解决了这个问题?