I have a C function that takes an array of structures as an argument, and I want to call this function from Java by way of SWIG, but the documentation seems quite murky on this subject and I can't find any * questions that directly address this case. Here is an example that is similar to what I want to do:
我有一个C函数,它接受一个结构数组作为参数,我想通过SWIG从Java调用这个函数,但文档在这个主题上似乎很模糊,我找不到任何直接解决的*问题这个案例。这是一个类似于我想要做的例子:
C header file:
C头文件:
typedef struct {
int timeToPayment;
double paymentAmount;
} Payment;
double presentValue(Payment *payments, int nPayments);
Java code snippet:
Java代码段:
...
Class Payment {
public int timeToPayment;
public double paymentAmount;
};
...
Payment[] payments = new Payment[3];
payments[0].timeToPayment = 30;
payments[0].paymentAmount = 1.0;
payments[1].timeToPayment = 60;
payments[1].paymentAmount = 2.0;
payments[2].timeToPayment = 90;
payments[2].paymentAmount = 3.0;
double pv = CLIBRARY.presentValue(payments);
// also acceptable: double pv = CLIBRARY.presentValue(payments, payments.length);
How can this be accomplished?
如何实现这一目标?
EDIT: to provide additional information, SWIG is a requirement because it is already used to incorporate simpler interfaces into the same Java codebase and supporting more than one approach for solving this problem will not be acceptable. Also, the signature of the C functions can't be changed and this example has been extremely simplified; the actual problem involves multiple C functions with signatures requiring arrays of structs (multiple arrays of different structs in some cases) and some of the structs are quite large, so I would really, really prefer not to have to break them up into equivalent arrays of primitive types.
编辑:为了提供附加信息,SWIG是一项要求,因为它已经被用于将更简单的接口合并到同一个Java代码库中,并且支持多种方法来解决这个问题是不可接受的。此外,C函数的签名不能改变,这个例子已经非常简化;实际问题涉及多个C函数,签名需要结构数组(在某些情况下有多个不同结构的数组),而且有些结构非常大,所以我真的非常希望不必将它们分解成等效的数组原始类型。
1 个解决方案
#1
0
In the end, I was unable to make this work (although I'm not saying that it isn't possible to do), and I created a translation layer in C that wraps everything into a single struct before passing it through.
最后,我无法完成这项工作(虽然我并不是说不可能这样做),我在C中创建了一个转换层,它将所有内容包装到单个结构中,然后再通过它。
#1
0
In the end, I was unable to make this work (although I'm not saying that it isn't possible to do), and I created a translation layer in C that wraps everything into a single struct before passing it through.
最后,我无法完成这项工作(虽然我并不是说不可能这样做),我在C中创建了一个转换层,它将所有内容包装到单个结构中,然后再通过它。