在我的软件应用程序中,我使用 JNA 从 Java 使用 C++ 中的本机库。我需要一个回调函数,将复杂的 java 对象返回给 C++。
这可能是一个简单的问题,但我没有使用 C++ 或 JNA 的经验,并且我无法成功地将 java 对象返回给 C++。
我遇到的大多数 JNA 回调函数示例都很简单,要么不返回任何内容,要么返回简单的本机类型。
我的本机代码如下所示
typedef const char* SMC_String;
int doNativeProcessing(SMC_String identifier, SMC_String lastName, SMC_String firstName)
typedef struct SimpleStruct
{
int myInt;
SMC_String myString;
} SimpleStruct;
typedef SimpleStruct* (*GetSimpleStruct_Callback)(SMC_String identifier);
...
// function that gets called from Java
int doNativeProcessing(SMC_String identifier, SMC_String lastName, SMC_String firstName)
{
cout << "In native function" << endl;
...do some processing...
callMyCallback();
return 0;
}
// function that calls the callback
void callMyCallback()
{
SimpleStruct *retSimpleStruct = GetSimpleStruct_Callback("id");
cout << "returned int: " << retSimpleStruct->myInt << endl;
cout << "returned string: " << retSimpleStruct->myString << endl;
}
爪哇代码:
public class SimpleStruct extends Structure {
public static class ByReference extends SimpleStruct implements Structure.ByReference
{}
public SimpleStruct() {
super();
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("myInt", "myString");
}
public int myInt;
public String myString;
}
...
public class GetSimpleStructCB implements Callback {
public SimpleStruct.ByReference callback(final String requestId) {
System.out.println("In Java callback");
final SimpleStruct.ByReference retVal = new SimpleStruct.ByReference();
retVal.myInt = 25;
retVal.myString = "Hello World!";
return retVal;
}
}
public static void main(String[] args) {
nativeLibrary = (NativeLibrary) Native.loadLibrary("my_native_dll", NativeLibrary.class);
nativeLibrary.doNativeProcessing("id", "Doe", "John");
}
当我运行应用程序时,输出是
In native function
In Java callback
returned int: 0
returned string: <blank value>
而不是预期的
In native function
In Java callback
returned int: 25
returned string: Hello World!
你能帮我弄清楚我做错了什么吗?非常感谢您的帮助。
慕村9548890
相关分类