我有这个java测试
package ftct;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.win32.StdCallLibrary;
import java.util.Date;
public class LibFTCT {
public LibFTCT() {
}
public interface LibFTCTLib extends StdCallLibrary {
LibFTCTLib INSTANCE = (LibFTCTLib) Native.loadLibrary(
"FTCTLib", LibFTCTLib.class);
int a(int x);
int DoCommand(int Command, int Param);
int GetDataRecord(int RecordNum, int StreamNum, Date ReadingTime,
double AIN1, double AIN2, double AIN3, double AIN4);
}
}
它调用 Delphi DLL。如果在 Delphi 中将参数作为 var 放置,Java 就会崩溃。否则它们是只读的。
我希望 GetDataRecord 以 RecordNum 等形式返回数据。如何在 java 中执行此操作?
最佳答案
您需要将参数声明为特殊类型,以传达它们是通过引用传递的事实。那么如果Delphi参数是这样的:
procedure Foo(var i: Integer; var d: Double);
您可以将其映射到 Java 函数,如下所示:
void Foo(IntByReference i, DoubleByReference d);
并调用该函数:
IntByReference iref = new IntByReference();
DoubleByReference dref = new DoubleByReference();
INSTANCE.Foo(iref, dref);
int i = iref.getValue();
double d = dref.getValue():
documentation 中对此进行了详细介绍。 :
Using ByReference Arguments
When a function accepts a pointer-to-type argument you can use one of the ByReference types to capture the returned value, or subclass your own. For example:
// Original C declaration void allocate_buffer(char **bufp, int* lenp); // Equivalent JNA mapping void allocate_buffer(PointerByReference bufp, IntByReference lenp); // Usage PointerByReference pref = new PointerByReference(); IntByReference iref = new IntByReference(); lib.allocate_buffer(pref, iref); Pointer p = pref.getValue(); byte[] buffer = p.getByteArray(0, iref.getValue());
Alternatively, you could use a Java array with a single element of the desired type, but the ByReference convention better conveys the intent of the code. The Pointer class provides a number of accessor methods in addition to getByteArray() which effectively function as a typecast onto the memory.
Type-safe pointers may be declared by deriving from the PointerType class.
关于java - 如何获取对 DLL 的 java JNA 调用以获取参数中返回的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17380916/