gpt4 book ai didi

java - 在 Java 上加载一个 dll 库

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:52 25 4
gpt4 key购买 nike

我需要在 java 上加载一个用 C 编写的库。我只有 dll 和头文件。 由于我不明白如何从 JNI 文档中翻译指针或其他派生类型,我尝试为此使用自动化工具 gluegen 和 SWIG,但我不知道如何使用它们。

我试图为 SWIG 创建一个接口(interface)文件,但它只给出了错误。是否有关于如何使用任何有效的工具将 dll 加载到 java 程序的示例,并且可以从 .h 文件生成翻译的 C 函数和类型?

最佳答案

这是一个 JNI 示例,说明如何在 Java 中执行 CRC32:

CRC32.java :

public class CRC32 {
// JNI function must be declared native
public static native int crc32(int crc, final byte[] buf);
/*
public static void main(String[] argv) {}
*/
static {
System.loadLibrary("crc32"); // Load your dll with System.loadLibrary
}
}

使用 javah -jni <Classname>创建头文件 CRC32.h :

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class CRC32 */

#ifndef _Included_CRC32
#define _Included_CRC32
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: CRC32
* Method: crc32
* Signature: (I[B)I
*/
JNIEXPORT jint JNICALL Java_CRC32_crc32
(JNIEnv *, jclass, jint, jbyteArray);

#ifdef __cplusplus
}
#endif
#endif

CRC32.c :此文件显示了 JNI 用法的示例:

/* For a look at the actual CRC32 algorithm, look at zlib's crc32.c */

#include <jni.h>
#include <stddef.h>
#ifdef _MSC_VER
typedef unsigned __int8 uint8_t;
typedef unsigned __int32 uint32_t;
#else
# include <stdint.h>
#endif

#include "CRC32.h"

uint32_t crc32(uint32_t crc, const void *const buf, size_t len);


uint32_t crc32(uint32_t crc, const void *const buf, size_t len) {
(void)crc;
(void)buf;
(void)len;
return 0;
}

JNIEXPORT jint JNICALL Java_CRC32_crc32(JNIEnv *jenv, jclass jcls,
jint jcrc, jbyteArray jbuf)
{
size_t len;
uint32_t crc;
jint scrc;
const void *buf;
jthrowable exc;
len = (*env)->GetArrayLength(env, jbuf);
crc = *((uint32_t *)&jcrc);
buf = (*env)->GetPrimitiveArrayCritical(env, jbuf, 0);
crc = crc32(crc, buf, len);
(*env)->ReleasePrimitiveArrayCritical(env, jbuf, buf, 0);
*((uint32_t *)&scrc) = crc;
return scrc;
}

希望对您有所帮助。

关于java - 在 Java 上加载一个 dll 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8116432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com