javacpp实践

2023-01-13 09:35:47

下面记录的是自己在使用javacpp过程中的代码。整个工程是在java里面调用别人的dll。自己写一个中间代理c程序,由java调用自己的c,然后自己的c调用其它人的dll。实践里面使用了主流的传参方式,其它传参请参考api。

前提工作:

下载javacpp.jar,安装visual studio

1.编写java代码:



import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;

@Platform(include="ZLPrint.h")
public class ZLPrint extends Pointer {
	static {
		Loader.load();
	}
	private static ZLPrint	s_print	= null;

	public final static ZLPrint getSingleton() {
		if (s_print == null) {
			s_print = new ZLPrint();
		}
		return s_print;
	}
	

	private ZLPrint() {
		allocate();
	}

	

	private native void allocate();

	// 初始化
	public native int init(int port);

	public native int get_printstatus();

	public native int get_booklet_page(IntPointer page);

	public native int get_booklet_id(BytePointer buf, IntPointer length);

	

	public static void main(String[] args) {
		
		System.out.println("test");
		
	}
	
}

保存为ZLprint.java

2.编写c代码


#ifdef ZLPRINT_EXPORTS
#define ZLPRINT_API  extern "C" __declspec(dllexport)
#else
#define ZLPRINT_API	 extern "C" __declspec(dllimport)
#endif

#include <string>

ZLPRINT_API int zl_init(int port);
ZLPRINT_API int zl_get_printstatus(void);
ZLPRINT_API int zl_get_booklet_page(int* page);
ZLPRINT_API	int zl_get_booklet_id(char* buf, int* length);

#pragma comment(lib, "D:/引用其他dll")

	class ZLPrint{
		public :
			
			int init(int port){ return ::zl_init(port);};
			
			int get_printstatus(){return ::zl_get_printstatus();};
			
			int get_booklet_page(int* page){return zl_get_booklet_page(page);};
			
			int get_booklet_id(signed char* buf, int* length){return zl_get_booklet_id((char *)buf,length);};
			
	};

保存为ZLprint.h格式

把上面两个源码文件放在同一个目录里面。保证在全局能直接java命令。在visual studio里面找到cmd命令窗口,比如:vs2012 x64 native Tools Command,在cmd里面进入到两个文件的目录,执行:

javac -cp javacpp.jar ZLPrint.java

ava -jar javacpp.jar ZLPrint

保证每步都不会出错,如果会出错,请检查。

如果指令正确,第一步会获得ZLprint.class文件,第二步获得:jniZLprint.dll、jniZLprint.exp、jniZLprint.lib、jniZLprint.obj四个文件。

  • 作者:大仕忆
  • 原文链接:https://blog.csdn.net/m0_37549050/article/details/89716277
    更新时间:2023-01-13 09:35:47