我有一个用C ++创建的DLL。非常简单。 DLL旨在执行加法,减法,乘法和除法。这是该代码:
#include "Math.h"
using namespace std;
long addition(long a, long b) {
return a + b;
}
long subtraction(long a, long b) {
return a - b;
}
long multiplication(long a, long b) {
return a * b;
}
long division(long a, long b) {
// Make sure neither variables are 0 to avoid errors
if (b != 0 && a != 0)
return a / b;
else
return 0;
}
int testReturn() {
return 7;
}
#ifdef MATH_EXPORTS
#define MATH_API __declspec(dllexport)
#else
#define MATH_API __declspec(dllimport)
#endif
extern "C" MATH_API long addition(long a, long b);
extern "C" MATH_API long subtraction(long a, long b);
extern "C" MATH_API long multiplication(long a, long b);
extern "C" MATH_API long division(long a, long b);
extern "C" MATH_API int testReturn();
编译后,此代码为我提供了文件Math DLL.dll
和Math DLL.lib
。
我知道您可以在另一个这样的C ++程序中运行此程序:
#include <iostream>
#include <Windows.h>
#include "tchar.h"
typedef int(__stdcall* importFunction)();
using namespace std;
int main() {
HINSTANCE hGetProcIDDLL = LoadLibrary(_T("Math DLL.dll"));
if (hGetProcIDDLL == NULL) {
cout << "Cannot locate the DLL file." << endl;
}
else {
cout << "Found the DLL file!" << endl;
}
importFunction testReturn = (importFunction)GetProcAddress(hGetProcIDDLL, "testReturn");
if (!testReturn) {
cout << "Could not locate the function" << endl;
}
else {
cout << "testReturn() returned " << testReturn() << endl;
}
}
但是如何用Eclipse Photon在Java中做到这一点?
答案 0 :(得分:0)
这是一个过程,但对我来说似乎很好。首先,从here下载JNA库。在zip文件中,您将找到.jar
文件。右键单击您的项目,然后转到 Build Path> Configure Build Path 。
这应该会自动将您带到 Libraries 标签,但如果没有,请单击它。然后点击右侧的添加外部JAR 按钮,找到JNA .jar
文件。
现在,您的项目中已有必要的库,请创建一个名为“ MathDLL”的新类。在这里,您可以输入以下代码:
import com.sun.jna.Library;
import com.sun.jna.Native;
/** Simple example of native library declaration and usage. */
public class MathDLL {
public interface mathDLL extends Library {
mathDLL INSTANCE = (mathDLL) Native.loadLibrary("Math DLL", mathDLL.class);
// Function definition
long addition(long a, long b);
long subtraction(long a, long b);
long multiplication(long a, long b);
long division(long a, long b);
}
public static void main(String[] args) {
mathDLL dll = mathDLL.INSTANCE;
// 500 + 531
long additionResult = dll.addition(500, 531);
// 250 - 12
long subtractionResult = dll.subtraction(250, 12);
// 12 * 12
long multiplicationResult = dll.multiplication(12, 12);
// 400 / 20
long divisionResult = dll.division(400, 20);
System.out.println("Addition (should be 1031): " + additionResult + ", Subtraction (should be 238): " + subtractionResult + ", Multiplication (should be 144): " + multiplicationResult + ", Division (should be 20): " + divisionResult);
}
}
此代码会将您的DLL添加到您的代码中(确保您的DLL与Java项目运行在同一文件夹中),定义函数,在编译过程中将其定位在DLL中,并允许您输入值和获取返回值用Java轻松实现!
.dll
。该程序知道它正在寻找.dll
,并且如果您提供一个错误,将返回错误。我知道我回答了自己的问题,但我希望我能帮助某人找到答案,他们正在寻找更轻松,运行更少的东西。