I'm newbee with JNA programing, the task I want to accomplish is:
C++ library exposes functionality to "put" a buffer in to a file and "lookup" a buffer. I compiled a shared object (.so) for this library with the header file providing the function definitions under "extern "C" " to make it C compiler friendly.
Test java program to access the buffers.
The code looks like this:
C/C++ code:
extern "C"
{
int get(int length, char *buffer);
}
#include <iostream>
#include <string.h>
int get(int length, char *buffer)
{
char *newBuff = new char[length];
for (int i = 0; i < length; ++i)
{
newBuff[i] = 'a';
}
memcpy(newBuff, buffer, length);
delete newBuffer;
return length;
}
java code:
import com.sun.jna.Library;
import com.sun.jna.Memory;
import com.sun.jna.Native;
public class TestJna
{
public static interface TestNative extends Library
{
int get(int length, Memory buffer);
}
private static final TestNative lib_ = (TestNative)Native.loadLibrary("libsample.so", TestNative.class);
public static void main(String[] args)
{
int length = 1024;
Memory buffer = new Memory(length);
int ret = lib_.get(length, buffer);
System.out.println("ret:" + ret + ":buffer:" + buffer.toString());
}
}
On running the program I get below error message on invocation of "lib.get()" method:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'get': dlsym(0x7f8d08d1e7d0, get): symbol not found
I was able to make it work by modifying code as follows:
public static interface TestNative extends Library
{
int get(int length, Pointer buffer);
}
Pointer was obtained by:
Pointer bfPtr = Native.getDirectBufferPointer(buffer); // buffer points to ByteBuffer allocated as direct NIO buffer.