c++qtjava-native-interfaceqt-resource

Failing to use DefineClass (JNI) with a Qt Resource


I'm attempting to use DefineClass which is part of the Java Native Interface. The method takes a const jbyte* which is a const signed char* and I'm trying to parse it from a Qt resource. But there has to be something wrong, as ExceptionDescribe() prints java.lang.ClassFormatError: Truncated class file.

QFile qfile(":/SomeClass.class");
qfile.open(QFile::ReadOnly)

QByteArray qbytes = qfile.readAll();
char *test = qbytes.data();
jbyte *buf = reinterpret_cast<jbyte*>(test);

jclass processorCls = env->DefineClass("example/SomeClass", nullptr, buf, sizeof(buf)); 

if (env->ExceptionCheck())
{
    env->ExceptionDescribe();
    env->ExceptionClear();
}

I can verify that the resource works, as I was able to print the content of the qfile with a method found here.

void read(QString fName)
{
    QFile file(fName);
    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        std::cout << "Could not open the file for reading" << std::endl;
        return;
    }

    QTextStream in(&file);
    QString text = in.readAll();

    std::cout << text << std::endl;

    file.close();
}

Solution

  • The sizeof(buf) returns the size of the pointer, not the size of the buffer. Please use the qbytes.size() instead.