![](/img/trans.png)
[英]How do I obtain a Structure.ByReference from a Structure using JNA?
[英]JNA Structure ByReference
下方的方法以及该方法的单元测试。 问题是我无法从Load方法返回结果的值。 以下单元测试失败!
我认为默认情况下,JNA的对象默认为ByRef,因此我尝试实例化并“无”传递LoadResults。ByReference...
我的错误在哪里?
@Test
public void testLoad () {
MY_Processor proc = new MY_Processor();
// LoadResults result = new LoadResults ();
LoadResults.ByReference result = new LoadResults.ByReference();
ByteByReference [] pathToFile = new ByteByReference[256];
// fill pathToFile out ...
try {
proc.Load (pathToFile, result);
assertEquals(0, result.errorCode);
assertEquals(1, result.elaborationTime);
assertEquals(2, result.coreItem);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Integer Load ( ByteByReference[] pathToFile,
LoadResults.ByReference result ) throws Exception {
// here result is correctly filled out !
LoadResults result = null;
result = native.getResult (numCore);
}
添加了本机代码。
UPDATE
// header
typedef struct
{
int errorCode;
int elaborationTime;
int coreItem;
} LoadResults;
//[in] path
//[out] result
int Load (char path[MY_BUFFER_DEFINE], LoadResults* result);
// implementation ...
LoadResults* getResult (int numCore)
{
// some check ...
LoadResults *localResult = new LoadResults();
// fill out ...
return localResult;
}
本机代码公开了一个“免费”方法,但是为了保持对我的问题的关注,我没有显示它:-)
/ UPDATE
谢谢!
O.
问题是您要传递一个Structure
作为参数,然后在函数中重新分配该参数。 这对论点毫无影响。
您需要遵循的模式是这样的:
Pointer p = mylib.getResult()
MyStructure m = new MyStructure(p);
// ....
mylib.free(p);
我建议您传入一个本地字符串( const char*
)作为路径,而不是一个固定大小的本地char
缓冲区。
UPDATE
如果要将结果复制到参数中,则需要复制结构的内容,例如
public int Load(LoadResults arg) throws Exception {
// Effectively copy memory from result into arg
LoadResults result = native.getResult(numCore);
if (alternative_1) {
// Copy result's native memory into arg's memory, then sync Java fields
result.useMemory(arg.getPointer());
result.write();
arg.read();
}
else {
// Sync result's native memory with arg's Java fields
Pointer p = arg.getPointer();
arg.useMemory(result.getPointer());
arg.read();
arg.useMemory(p);
}
}
刚解决...
1)我不需要使用LoadResults.ByReference
。
2)问题是在Load方法中,我用另一个输入更新了输入中传递的引用:
public Integer Load ( ByteByReference[] pathToFile, LoadResults result ) throws Exception
{
// that's the problem!!!! storing the value into another object with another "address"
// and not the original "results".
// result = native.getResult (numCore);
// solved with this:
native.getResult (numCore, result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.