我在C#中的方法,這是我從.DLLC#出的IntPtr相當於在Java中
[DllImport("somedll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int find([MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 64)] string atr, out IntPtr int);
[DllImport("somedll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int getData(IntPtr int, int dataId, byte[] dataBuffer, ref int dataBufferSize);
調用這個方法C#調用如下
static IntPtr number = IntPtr.Zero;
static int res = 0;
try{
number = IntPtr.Zero;
res = find(null, out number);
if (number == IntPtr.Zero)
throw new ApplicationException("Something is wrong");
uint dataBufferSize = 1024;
res = getData(number, 1, null, ref dataBufferSize);
}
我沒有發現什麼在Java中是相同的。
如果我不喜歡這樣寫道:
public int find(String atr, Pointer int);
它說
java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeInt(Native Method)
at com.sun.jna.Function.invoke(Function.java:419)
at com.sun.jna.Function.invoke(Function.java:354)
at com.sun.jna.Library$Handler.invoke(Library.java:244)
如果我不喜歡這樣寫道:
public int find(String atr, IntByReference int);
什麼也沒有發生。
Java代碼
IntByReference iref = new IntByReference();
res = find(null, iref);
Pointer pointer = iref.getPointer();
int dataBufferSize = 1024;
byte[] dataBuffer = new byte[dataBufferSize];
res = getData(Pointer.nativeValue(pointer), 1, dataBuffer, dataBufferSize);
find返回0,這意味着OK,但返回的getData 6,這意味着內存地址也不好。通過什麼也沒有發生我的意思是任何其他res比0.
所以,也許你應該放棄C#的標籤,並添加JNI,JNA或標籤? –
(我的意思是,你根本不需要添加任何標籤,如果你願意的話,甚至可以使用完全誤導性的標籤,但那些可能提供答案的人可能不會看到你的問題。) –
可能的重複[如何做相當於Java基元的引用傳遞](http://stackoverflow.com/questions/5614562/how-to-do-the-equivalent-of-pass-by-reference-for -primitives-in-java) – kennytm