我正在尝试通过 JNI 在 Java 程序中使用外部 C 库。我需要使用两个函数,第一个是 C 中的计算并将一些结果存储在 double 组中,第二个函数然后返回指向该 double 组的指针。
我现在的问题是如何在 Java 中访问/使用这个双数组。
JNI 代码:
JNIEXPORT jdoubleArray JNICALL Java_rna_jni_ViennaRNAInterface_getBasePairingProbabilities(JNIEnv *env, jobject thisObj, jstring sequence){
jdoubleArray dArray;
const char *seq= (*env)->GetStringUTFChars(env,sequence,0);
// Calculates a single value, stores important results in double array
pf_fold_par(seq,NULL,NULL,1,0,0);
// export_bppm() returns pointer to double array
double* pr = export_bppm();
// Processing of double array
return dArray;
}
C 库中的代码基本上如下所示,
FLT_OR_DBL
定义为 Float 或 Double:
PRIVATE FLT_OR_DBL *probs=NULL;
PRIVATE void get_arrays(unsigned int length){
size = sizeof(FLT_OR_DBL) * ((length+1)*(length+2)/2);
probs = (FLT_OR_DBL *) space(size);
}
PUBLIC float pf_fold_par(const char *sequence,char *structure, pf_paramT *parameters,int calculate_bppm,int is_constrained, int is_circular){
float result;
int n = (int) strlen(sequence);
get_arrays(n);
/*
* Calculating result
*/
// Fill double array
pf_create_bppm(sequence, structure);
pr = probs;
return result;
}
如果有必要,我也可以在库中提供确切的实现。
\edit:精确实现位于 http://pastebin.com/ayGg2HBR
最佳答案
你知道返回了多少个双指针吗?如果没有,您首先需要计算它,然后:
// export_bppm() returns pointer to double array
double* pr = export_bppm();
//Determine # of doubles @ pr; didn't test this, just guessing at result structure
int count = 0;
double *start = pr;
while( start++ != null )
count++;
// Processing of double array
jdoubleArray dArray = env->NewDoubleArray( count );
env->SetDoubleArrayRegion( dArray , 0, count, pr );
return dArray;
关于java - 使用 JNI 将指向 double 组的 C 指针传递给 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20054652/