Recently, an advertisement publishing platform written by myself needs to be migrated to the Linux platform. Since the dll file of the windows platform was used, we need to switch to. so. This section describes how to call. so in Linux.
When using jna to call a local method in linx, You need to compile the program written in C as a so file.
1. Write a simple test. c file:
[Cpp]
# Include <stdio. h>
Int add (int a, int B );
Int add (int a, int B)
{
Int c = a + B;
Return c;
}
2. Compile as so Dynamic Link Library:
[Cpp]
Gcc-fpic-c test. c
Gcc-shared-o libtest. so test. o
Ls:
Libtest. so test. c test. o
This will generate the so file. Why is the name libtest. so instead of test. so? Because when looking for the so file, jna needs to match the so file prefixed with lib
3. Start to write the java file (jna. jar needs to be downloaded). Let's write a TestSo. java:
[Java]
Import com. sun. jna. Library;
Import com. sun. jna. Native;
Public class TestSo {
Public interface LgetLib extends Library {
// Call the so file in linux. Note that you only need to write test here. Do not write libtest or add a suffix.
LgetLib INSTANCE = (LgetLib) Native. loadLibrary ("test", LgetLib. class );
Int add (int a, int B );
}
Public int add (int a, int B ){
Return LgetLib. INSTANCE. add (a, B );
}
Public static void main (String [] args ){
TestSo ts = new TestSo ();
Int c = ts. add (10, 20 );
System. out. println ("10 + 20 =" + c );
}
}
4. Compile the following code:
[Plain]
Export CLASSPATH = $ CLASSPATP:./jna. jar // set the environment variable.
Javac TestSo. java
Run TestSo directly here:
[Java]
Java TestSo
Exception in thread "main" java. lang. UnsatisfiedLinkError: Unable to load library 'test': libtest. so: cannot open shared object file: No such file or directory
At com. sun. jna. NativeLibrary. loadLibrary (NativeLibrary. java: 163)
At com. sun. jna. NativeLibrary. getInstance (NativeLibrary. java: 236)
At com. sun. jna. Library $ Handler. <init> (Library. java: 140)
At com. sun. jna. Native. loadlibraries (Native. java: 379)
At com. sun. jna. Native. loadlibraries (Native. java: 364)
At TestSo $ LgetLib. <clinit> (TestSo. java: 7)
At TestSo. add (TestSo. java: 11)
At TestSo. main (TestSo. java: 15)
This error indicates that the so file cannot be found. So we set the directory where the so file is located to the environment variable LD_LIBRARY_PATH:
Vim/etc/profile
Add
Export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH: $ {Your so directory}
Then, you can check whether the setting is effective: echo $ LD_LIBRARY_PATH. If the content you set appears, you can open a window and check again.
After setting the environment variables, you can run the java class:
Java TestSo
10 + 20 = 30
This operation is successful.
If you encounter an emergency, and this is not the case, you can temporarily submit the so file to the directory/usr/lib, which generally enables the program to run.