Delphi或FreePascal
string是不能用作JNA类型的托管类型。所述JNA文档解释的Java
String被映射到的指针的8个字符的空终止阵列。用Delphi的说法是
PAnsiChar。
因此,您可以将Pascal代码中的输入参数从
string更改为
PAnsiChar。
返回值存在更多问题。您将需要确定谁分配内存。分配它的人也必须释放它。
如果本机代码负责分配它,那么您需要堆分配以null终止的字符串。并返回指向它的指针。您还需要导出一个解除分配器,以便Java代码可以要求本机代码解除对堆分配的内存块的分配。
在Java代码中分配缓冲区通常更方便。然后将其传递给本机代码,并让其填写缓冲区的内容。这个堆栈溢出问题以Windows
API函数
GetWindowText为例说明了该技术:如何使用JNI或JNA读取窗口标题?
使用Pascal的示例如下:
function GetText(Text: PAnsiChar; Len: Integer): Integer; stdcall;const S: AnsiString = 'Some text value';begin Result := Length(S)+1;//include null-terminator if Len>0 then StrPLCopy(Text, S, Len-1);end;
在Java方面,考虑到我对Java完全一无所知,我想代码看起来像这样。
public interface MyLib extends StdCallLibrary { MyLib INSTANCE = (MyLib) Native.loadLibrary("MyLib", MyLib.class); int GetText(byte[] lpText, int len);}....int len = User32.INSTANCE.GetText(null);byte[] arr = new byte[len];User32.INSTANCE.GetText(arr, len);String Text = Native.toString(arr);


