Search code examples
javac++jna

Input Mismatch JNA


In working with JNA, I've had a very odd issue appear. Here is my C++ code. -- Reduced for simplicity --

#include <iostream>

extern "C" std::string func(int, int, int, double*, double*);

std::string func(int a, int b, int c, double* data1, double* data2) {
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
    return "Finished";
}

Here is the Java class:

class CLibOperator {
    interface CLib extends Library {
        CLib INSTANCE = 
            (CLib) Native.loadLibrary("libFile.so", CLib.class);

        String func(int a, int b, int c, double[] data1, double[] data2);
    }

    public static void main(String[] args) {
        double[] d1 = {10,20,30};
        double[] d2 = {111,222,333,444,555,666,777};
        CLib.INSTANCE.func(1, 2, 3, d1, d2);
    }
}

The output of the C function, however, is:

2
3
3856103913

What I expected is:

1
2
3

It seems like the first argument is being completely ignored. Any thoughts on how to resolve this issue?


Solution

  • You're attempting to return std::string from a function which has C-linkage specified (extern "C"). I'm surprised that your compiler doesn't complain to you about this. When returning structs or classes by value, it's common for a compiler (of course, depending on the compiler and the ABI it uses) to generate code which essentially equals to the struct being passed to the caller as a pointer passed to the function as a parameter.

    Change the return type to const char *.

    extern "C" const char *func(int, int, int, double *, double *);
    

    You might also be interested in reading: Functions with C linkage able to return class type?