利用JNA使Java訪問本地C++

鍾超發表於2011-08-29

(1)C++程式碼

typedef int (*CB_OnServiceUserMessage)(uint32_t cid, uint32_t uid, const std::string& data);
extern "C"
{
   void init(CB_OnMsg cb_OnMsg)
   {
      (*cb_OnMsg)();
      std::cout << "Initializing..." << std::endl;
   }
   void start()
   {
      std::cout << "Start up!" << std::endl;
   }
   void stop()
   {
      std::cout << "Shut down!" << std::endl;
   }
   void send(char* msg)
   {
      std::cout << msg << std::endl;
   }
}


(2)Java程式碼

PluginProxy.java

import java.io.IOException;
import java.lang.management.ManagementFactory;

import com.sun.jna.Callback;
import com.sun.jna.Library;
import com.sun.jna.Native;

public class PluginProxy
{
	private static String libPath;    
	private interface LibPluginProxy extends Library
	{
		static LibPluginProxy INSTANCE = (LibPluginProxy) Native.loadLibrary(libPath, LibPluginProxy.class);
		public void init(Callback callback);
		public void start();
		public void stop();
		public void send(String msg);
	}

	public static void main(String[] args) throws Exception {
		libPath = "libPluginProxy.so";
		LibPluginProxy.INSTANCE.init(new CB_OnMsg());
		System.out.println("in main function.");
		
		//add shutdown hook
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			@Override
			public void run() {
				Native.unregister(LibPluginProxy.class);
				System.out.println("stop..");
				LibPluginProxy.INSTANCE.stop();

				String n = ManagementFactory.getRuntimeMXBean().getName();
				if (n == null) return;
				String pid = n.substring(0, n.indexOf("@"));
				if (pid == null) return;
				try
				{
					Runtime.getRuntime().exec("kill -9 " + pid);
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}

				System.exit(-1);
			}
		}));
		Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				LibPluginProxy.INSTANCE.start();
				System.out.println("started in thread..");
			}
		});
		
		t.start();	
		
		System.out.println("started!!");
	}
}


CB_OnMsg.java

import com.sun.jna.Callback;

public class CB_OnMsg implements Callback {

	// 應用建立
	public final int onMsg() {
		System.out.println("CB_OnMsg, in function onMsg.");
		return 0;
	}
	
}

(3)編譯C++的.so共享庫

編寫makefile,細節忽略,只提供最主要的command,如下:

g++ -shared -o libplugin.so -fPIC -Wall -ggdb -D_REENTRANT -DHAVE_EPOLL -DXML_NULL -DSTATUS_NEWPROTOCOL -Wl,-rpath,../bin
#注:此段有多餘的flags,有待修改...


(4)生成Java的JAR包

在eclipse中生成JAR包,linux生成JAR命令請Google......

(5)執行JAR包呼叫.so共享庫

在linux下輸入命令:

java -cp jna-3.3.0.jar:ss.jar SalmonProxy 

相關文章