简体   繁体   中英

How to pass a pointer to a struct array to a function in java using JNA?

I need to pass pointer of an array of IplImage ( IplImage extends CvArray extends Structure implements cloneable ) to a function The native code in C is as follows:

cvCalcEigenObjects(
  nTrainFaces,
  (void*)faceImgArr,
  (void*)eigenVectArr,
  CV_EIGOBJ_NO_CALLBACK,
  0,
  0,
  &calcLimit,
  pAvgTrainImg,
  eigenValMat->data.fl);

I tried this:

cvCalcEigenObjects(
  nTrainFaces,
  faceImgArr[0].getPointer(),
  eigenVectArr[0].getPointer(),
  CV_EIGOBJ_NO_CALLBACK,
  0,
                null,
  calcLimit,
  pAvgTrainImg,
  eigenValMat.data.getFloatArray(0, Pointer.SIZE));

but it didn't work. The declaration of this function in Java is like this:

public static void cvCalcEigenObjects(int i, 
  Pointer pntr, 
  Pointer pntr1, 
  int i1, 
  int 2, 
  Pointer pntr2, 
  cxcore.CvTermCriteria ctc, 
  cxcore.IplImage ii, 
  FloatBuffer fb)

Your C prototype is quite unclear but I'll give you something that's not obvious at first glance in JNA but that might be the cause of your troubles.


When dealing with array of structures you need to do something like these :

// Syntax to get a new empty structure array (4 cells) to pass to a function
// which will populate it
MyStructureClass[] incomingStructArray = new MyStructureClass().toArray(4);

// Syntax to transform a standard java array to an array suitable 
// to be passed to a C function
MyStructureClass[] standardJavaStructArray = ....
MyStructureClass[] outgoingStructArray = new MyStructureClass().toArray(standardJavaStructArray);

Now if you wonder why one would need to do so (which is completly crazy from the java point of view) you need to remember you're not coding Java, you're coding C

A standard java array is in fact a void* but a standard C array is a MyStructure*

If MyStructure uses 12 Bytes in memory :

  • a 4 cell Java array of MyStructureClass uses 16 Bytes (= 4 cell x 4 Bytes per pointer) in memory (not entirely true but let say so ; if all cells != null then an additional 48 Bytes will be used for the MyStructureClass themselves )
  • a 4 cell C array of MyStructure uses 48 Bytes (= 4 cell x 12 Bytes per MyStructure)

That's why when using JNA and array of structures you need to be very carefull with what you do, beacause an array of structure is very different from an array of pointers to structure

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM