I am trying to run cpp code via Java using the Project Panama and I got an error because my library is not loading.
cpp code:
// MyRectangle.cpp
#include <iostream>
#include <cstring>
class Rectangle {
int width, height;
public:
Rectangle(int, int);
int area() {return width*height;}
};
Rectangle::Rectangle(int w, int h) {
this->width = w;
this->height = h;
}
// Expose C ABI for Panama to call into.
extern "C" int rectArea(int, int);
int rectArea(int w, int h) {
std::cout << "Inside C++ Code " << std::endl;
Rectangle rect(w,h);
return rect.area();
}
I compile by this: g++ -dynamiclib -current_version 1.0 -o libmyrectangle.dylib MyRectangle.cpp
and Java code:
class MyRectangle {
public static void main(String[] args) throws Throwable {
System.loadLibrary("myrectangle");
var cLinker = CLinker.systemCLinker();
// C function int rectArea(int w, int h)
MethodHandle rectAreaMH = cLinker.downcallHandle(cLinker.lookup("rectArea").get(),
FunctionDescriptor.of(ValueLayout.OfInt.JAVA_INT, ValueLayout.OfInt.JAVA_INT, ValueLayout.OfInt.JAVA_INT));
// Return area of rectangle
int w = 8;
int h = 2;
int area = (int) rectAreaMH.invokeExact(w, h);
System.out.printf("MethodHandle calling rectArea(%d, %d) = (%d)\n", w, h, area);
}
}
and I got error: Exception in thread "main" java.lang.UnsatisfiedLinkError: no myrectangle in java.library.path: ~/Users/project-panama-examples
It seems that java doesn't see my library, but why? Is it a bug?
Panama is not compatible yet with
arm64
, that is M1 MacBooks. I'm assuming yours is one of those?You can still run your code inside a docker container with x86_64 architecture. For my own experiments I put together this dockerfile.