I have following sample code in C++
class SomeClass: public ISomeClass
{
private:
int myMember;
public:
SomeClass(int value) : myMember(value) {}
__declspec(dllexport)
int GetCount() override
{
return myMember;
}
};
extern "C" __declspec(dllexport)
int doSomething(ISomeClass** someCl)
{
*someCl = new SomeClass(600);
return (*someCl)->GetCount() + 2;
}
And I'm successfully using this in Java with FFI with the following code:
try(Arena arena = Arena.ofConfined()) {
Linker linker = Linker.nativeLinker();
SymbolLookup my = SymbolLookup.libraryLookup("C:\\Path\\to\\my.dll", arena);
MethodHandle doSomething = linker.downcallHandle(
my.find("doSomething").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS)
);
MemorySegment someAddress = arena.allocate(ValueLayout.ADDRESS);
int res = (int)doSomething.invoke(someAddress);
System.out.println("Result is " + res);
}
catch (Throwable t)
{
System.out.println("Error is " + t.getMessage());
}
And it correctly outputs 602
.
My question is - how can I represent C++'s SomeClass
in Java, so that I can pass that representation from Java to C++ instead of MemorySegment someAddress
on the line doSomething.invoke(someAddress)
and that I can later use that representation to call ThatRepresentation->GetCount()
method directly on that class inside Java?
createSomeClass() / GetCount(ISomeClass* someCl) / doSomething(ISomeClass* someCl)
and then you can manage instances and whatever calls you want on C++ instance.