jna调用c 的dll(包含回调函数)

创建dll

.h

#ifndef __MAIN_H__
#define __MAIN_H__

#include <windows.h>

/*  To use this exported function of dll, include this header
 *  in your project.
 */

#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT extern   "C"  __declspec(dllimport)
#endif


typedef void ( * DecCBFun)(int a,int b) ;

DLL_EXPORT int InputData(int a);
DLL_EXPORT int SetDecCallBack(int a,DecCBFun decCBFun,long uUser);



#endif // __MAIN_H__
</pre><pre code_snippet_id="1566861" snippet_file_name="blog_20160127_3_693249" name="code" class="html">导出函数需要声明 extern   "C" 否则会报找不到指定模块


.cpp

#include "stdafx.h"
#include "JnaTestDll.h"
#include "Decode.h"
Decode dec;
int  InputData(int a){
	if(a==1)
		dec.MyDecCBFun(1,2);
	return 2;
}
int SetDecCallBack(int a,DecCBFun decCBFun,long uUser)
{
	dec.SetDecCBFun(decCBFun);
	return 1;
}


#pragma once
#include "JnaTestDll.h"
class Decode
{
public:
	Decode(void);
	~Decode(void);
	void (* MyDecCBFun)(int nPort,int b) ;
	void SetDecCBFun(DecCBFun decCNFun)
	{
		this->MyDecCBFun=decCNFun;
		
	}
};

#include "StdAfx.h"
#include "Decode.h"


Decode::Decode(void)
{
}


Decode::~Decode(void)
{
}

java 中调用

需引入类库jna.jar 和platform.jar

声明dll中的接口



public interface JnaTestDll extends Library {  
	public static JnaTestDll instanceDll  = (JnaTestDll)Native.loadLibrary("JnaTestDll",JnaTestDll.class);

	 interface JavaCallbackAdd extends Callback
     {
       int DecCBFun(int a,int b);
     }
	
	 int Mobile_InputData(int a);
	 int Mobile_SetDecCallBack(int a,JavaCallbackAdd decCBFun,long uUser); 
	 public static  JavaCallbackAdd callback=new JnaTestDll.JavaCallbackAdd()
	  {
		    @Override
			public int DecCBFun(int a, int b)
			{
				System.out.println("回调成功");
				return 0;
			}
	  };
}  

调用

public class Testdll
{

	public static void main(String[] args)
	{
		int test=JnaTestDll.instanceDll.Mobile_SetDecCallBack(1, JnaTestDll.callback, 1);
     <span style="white-space:pre">	</span>        for(int i=0;i<100;i++)
                {
        	  JnaTestDll.instanceDll.Mobile_InputData(i%10);
                }
	}

}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值