0

I'm trying to pass a Mat object through a JNI function using a jlong but I get this exception at runtime:

(__gnu_cxx::__verbose_terminate_handler()+276)
(__cxxabiv1::__terminate(void (*)())+8)
(std::terminate()+20)
(__cxa_throw+148)
(cv::error(cv::Exception const&)+80)
(cv::Mat::copySize(cv::Mat const&)+18)
(cv::Mat::Mat(cv::Mat const&)+122)
(cv::_InputArray::getMat(int) const+252)
(cv::split(cv::_InputArray const&, cv::_OutputArray const&)+20)
(cv::split(cv::Mat const&, std::vector<cv::Mat, std::allocator<cv::Mat> >&)+28)
(cv::xphoto::balanceWhite(cv::Mat const&, cv::Mat&, int, float, float, float, float)+54)
(Java_com_myapp_camera_CameraManager_simpleWhiteBalance+18)

The native function is defined like this

public native static void simpleWhiteBalance(Mat source, Mat dest);

and it's implemented in the following way

#include <jni.h>
#include <opencv2/core/core.hpp>
#include "opencv2/xphoto.hpp"
#include "simple_color_balance.cpp"
#include "com_myapp_camera_CameraManager.h"

JNIEXPORT void JNICALL Java_com_myapp_camera_CameraManager_simpleWhiteBalance
  (JNIEnv *, jclass, jlong in, jlong out) {

     cv::Mat& inMat = *(cv::Mat*)in;
     cv::Mat& outMat = *(cv::Mat*)out;

    cv::xphoto::balanceWhite(inMat, outMat, cv::xphoto::WHITE_BALANCE_SIMPLE);
}

I am new to C++, what does the exception mean?

2 Answers 2

1

jlong is not mapping an object but long (object is mapped as jobject) and Java instance of Mat is completely different from instance of cv::Mat and cannot be casted this way. The usual way here is to use longs in Java as approximation of pointers in C++ and cast it in the way you use.

Also, this is not an exception but a crash caused by uncaught exception. To get the exception, you would need to use try - catch in your C++ code. C++ exceptions are incompatible with Java exceptions and so you cannot throw in C++ and catch it in Java or vice versa.

2
  • Thanks, solved passing a long object through the Mat.getNativeObjAddress() Feb 11, 2015 at 10:05
  • ok, how to convert jlong to cv::Mat ? May 25, 2023 at 6:08
-1
cv::Mat *inMat = (cv::Mat*)in;
cv::Mat *outMat = (cv::Mat*)out;

and please pass pointer instead of references. see example

2
  • sorry,I guess he know what I mean, he must convert mat pointer to jlong
    – cloudtex
    Feb 11, 2015 at 9:09
  • Stupid question - little C++ experience - why pass a pointer rather than a reference?
    – WillC
    Mar 21, 2017 at 3:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.