0

我试图从 Java 代码中使用 .NET DLL,tsMemberFunctions.DLL已成功加载,但代码无法调用实际函数。

请参阅下面的片段:

public class tsMemberFunctions {  
    public native void GetMemberJSONSample();

    static {
        System.loadLibrary("tsMemberFunctions");
        System.out.println("Loaded");
    }

    public static void main(String[] args) {
        new tsMemberFunctions().GetMemberJSONSample();

    }
}

在执行上述方法时,我遇到以下错误:

Loaded
Exception in thread "main" java.lang.UnsatisfiedLinkError: tsMemberFunctions.GetMemberJSONSample()V
    at tsMemberFunctions.GetMemberJSONSample(Native Method)
    at tsMemberFunctions.main(tsMemberFunctions.java:12)

有人可以告诉我我是否遗漏了代码中的任何内容或任何不正确的地方,或者为此用例提出更好的替代方案。TIA。

4

1 回答 1

0

您必须非常小心名称和导出。

假设你有这个超级简单的库

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include "jni.h"
#include <stdio.h>

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

extern "C" JNIEXPORT void JNICALL Java_recipeNo001_HelloWorld_displayMessage

(JNIEnv* env, jclass obj) {

    printf("Hello world!\n");

}

您必须确保构建DLL正确的体系结构(这取决于您拥有的 Java 版本 - 32/64 位)。

假设你有x64 DLLand x64 JDK,你可以像这样调用你的 lib

package recipeNo001;

public class HelloWorld {

    public static native void displayMessage();

    static {
        System.load("C:\\Users\\your_name\\Source\\Repos\\HelloWorld\\x64\\Debug\\HelloWorld.dll");
    }

    public static void main(String[] args) {
      HelloWorld.displayMessage();
    }
}

在您的情况下,我敢打赌您extern "C"的代码中没有 - 这就是 JVM 找不到您的符号的原因。

在工具方面,我建议使用 Visual Studio 2019(在创建 DLL 时)和用于 Java 代码的 IntelliJ。

你可以在这里找到很多示例:http: //jnicookbook.owsiak.org/和这里:https ://github.com/mkowsiak/jnicookbook

于 2019-05-29T18:05:34.010 回答