vuis vuis - 11 months ago 120
Java Question

C# out IntPtr equivalent in Java

I have a methods in C# which I call from .dll

[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);

In C# call of this methods looks like this

static IntPtr number = IntPtr.Zero;
static int res = 0;
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);

I didn't find what would be equivalent in Java.

If I do it like this:

public int find(String atr, Pointer int);

It says

java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeInt(Native Method)
at com.sun.jna.Function.invoke(
at com.sun.jna.Function.invoke(
at com.sun.jna.Library$Handler.invoke(

If I do it like this:

public int find(String atr, IntByReference int);

Nothing happens.

Java code

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 returns 0, which means OK, but getData returns 6 which means that memory address is not good. By nothing happens I mean any other res than 0.

Answer Source

It works if I pass number.getValue() to getData. Now res is 0.

Complete code:

IntByReference number=new IntByReference(0);                        
res = find(null, number);                                   
int dataBufferSize = 1024;
IntByReference iref=new IntByReference(dataBufferSize);
Pointer array = new Memory(dataBufferSize);                         
res = getData(number.getValue(),1, array,iref);                 
byte[] dataBuffer=array.getByteArray(0,dataBufferSize); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download