I'm working on calling functions from a Delphi compiled *.so file from a Java program. After some research it seems like JNA is he way to go. Before diving into some complex Delphi code, I'm trying to play with some "Hello World" code but am having trouble getting a string returned by a Delphi function.
The Delphi code (helloworld.pp):
library HelloWorldLib;
function HelloWorld(const myString: string): string; stdcall;
begin
WriteLn(myString);
Result := myString;
end;
exports HelloWorld;
begin
end.
I compile it from the command line with "fpc -Mdelphi helloworld.pp", which produces libhelloworld.so.
Now my Java class:
import com.sun.jna.Library;
import com.sun.jna.Native;
public class HelloWorld {
public interface HelloWorldLibrary extends Library {
HelloWorldLibrary INSTANCE = (HelloWorldLibrary) Native.loadLibrary("/full/path/to/libhelloworld.so", HelloWorldLibrary.class);
String HelloWorld(String test);
}
public static void main(String[] args) {
System.out.println(HelloWorldLibrary.INSTANCE.HelloWorld("QWERTYUIOP"));
}
}
However when I run this Java code I get:
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007f810318add2, pid=4088, tid=140192489072384
#
# JRE version: 7.0_10-b18
# Java VM: Java HotSpot(TM) 64-Bit Server VM (23.6-b04 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C [libhelloworld.so+0xbdd2] HelloWorld+0x6fea
Note that if I change my Delphi method (and the associated Java interface) to return a hardcoded integer, everything works great: the string I pass gets printed and I get the int back as expected.
Strangely enough, if the Delphi method returns a char, I have to write my JNA proxy as returning a byte and cast it to char manually (if I declare my interface as returning a char it prints out a garbage character).
Any idea what is going wrong here?
FYI, I'm on Ubuntu 12.04, 64bits, using Sun JDK 1.7.0_10-b18, JNA 3.5.1 and Free Pascal Compiler version 2.4.4-3.1.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…