java连接c++动态库并生成jar包提供给别人调用
1、需要将java通过jni生成头文件,并导入到c++项目并对c++进行jni方法继承
在项目的src目录执行,否则会提示 错误:找不到符号
javac -encoding utf8 D:\project\DeviceDemo\src\com\javaCallDll\DemoController.java
javah -jni com.javaCallDemo.DemoController
2、c++是多线程回调,需要将当前线程注册到虚拟机中用到AttachCurrentThread
void TabletRemoteContollerRbtAdapter::onDeviceMac(rbt_win_context* context, const char* pMac) {
JNIEnv* pEnv;
gs_jvm->AttachCurrentThread((void **)&pEnv, NULL);
if (!pEnv) {
std::cout << "pEnv == null" << std::endl;
return;
}
jclass jClassTmp = pEnv->GetObjectClass(_correspondJavaClassInstance);
_onDeviceMacMethodID = pEnv->GetMethodID(jClassTmp, "onDeviceMac", "(Ljava/lang/String;)V");
if (!_onDeviceMacMethodID) {
std::cout << "_onDeviceMacMethodID is nullptr" << std::endl;
return;
}
jstring jMac = CStrToJStr(pEnv, pMac);
pEnv->CallVoidMethod(_correspondJavaClassInstance, _onDeviceMacMethodID, jMac);
}
3、在java 写主调函数和回调函数在主调初始化的时候将回调类做为参数传进去
public static final TabletRemoteController tabletRemoteController = new TabletRemoteController();
/**
* 初始化接口
* @param rbtDataCallBack
* @return
*/
public int init(RbtDataCallBack rbtDataCallBack) {
tabletRemoteController.setRbtDataCallBack(rbtDataCallBack);
int res= tabletRemoteController.init();
return res;
}
public class TabletRemoteController {
static {
System.loadLibrary("device");
System.loadLibrary("ControllerAdapter");
}
private RbtDataCallBack rbtDataCallBack;
public void setRbtDataCallBack(RbtDataCallBack rbtDataCallBack) {
this.rbtDataCallBack = rbtDataCallBack;
}
public void onOriginData(String mac, int s, int x, int y, int p, byte[] buffer, int len) {
rbtDataCallBack.onOriginData(mac, s, x, y, p, buffer, len);
}
4、将c++动态库回调数据进行处理的可以继承回调类接口
public interface RbtDataCallBack {
void onOriginData(String mac, int s, int x, int y, int p, byte[] buffer, int len);
void onDeviceMac(String mac);
}
public class SampleCode {
public static void main(String[] args) {
RbtDeviceWifi rbtDeviceWifi = new RbtDeviceWifi();
rbtDeviceWifi.init(new RbtDataCallBack() {
@Override
public void onOriginData(String mac, int s, int x, int y, int p, byte[] buffer, int len) {
System.out.println("mac=" + mac + " s=" + s + " x=" + x + " y=" + y + " p=" + p + " byte=" + buffer + " len=" + len);
}
5、将项目进行打包并提供动态库给客户
打开project Structure 选择+号 进行