创建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" 否则会报找不到指定模块
#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);
}
}
}