Structure array elements must use contiguous memory (bad backing address at Stru

JNA以结构体数组为参数进行调用:

 

// C++
// student 结构体定义
typedef struct  
{
	int age;
	char name[20];
}Student;

// 修改java对象的属性值
JNAAPI bool changeObjs(Student stu[],int size)
{
	for(int i=0;i<size;i++)
	{
		stu[i].age*=10;
		strcpy(stu[i].name,"wokettas");
	}
	return true;
}

/// Java
// JNA调用方法
Student[] stus=new Students[2];
Student s1=new Student();
Student s2=new Student();
s1.age=1;
s1.name=Arrays.copyOf("k1".getBytes(), 20);
s2.age=2;
s2.name=Arrays.copyOf("k2".getBytes(),20);
stus[0]=s1; //数组赋值
stus[1]=s2;
Gui.gui.changeObjs(stus, stus.length);

 

   运行报错:

        Structure array elements must use contiguous memory (bad backing address at Structure array index 1)

   结构体数组必须使用连续的内存区域, 上例s1,s2都是new出来的新对象,不可能连续; 也就是说传统方式的初始化数组不能解决, 查询JNA api发现里面提供了:

toArray

public Structure[] toArray(int size)
Returns a view of this structure's memory as an array of structures. Note that this Structure must have a public, no-arg constructor. If the structure is currently using a Memory backing, the memory will be resized to fit the entire array.
 

 修改后的代码:

// 测试对象数组
Student student=new Student();
Student[] stus=(Student[]) student.toArray(2); //分配大小为2的结构体数组
stus[0].age=1;
stus[0].name=Arrays.copyOf("k1".getBytes(), 20);
stus[1].age=2;
stus[1].name=Arrays.copyOf("k2".getBytes(),20);
Gui.gui.changeObjs(stus, stus.length);

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值