JNA 和 C++ - 导致不满意链接错误的简约示例

JNA and C++ - Minimalistic Example resulting in UnsatisfiedLinkError

本文关键字:错误 链接 不满意 C++ JNA      更新时间:2023-10-16

对于我当前的项目,我需要在我的java应用程序中使用一些C ++代码。在我看来,常见的解决方案是从 c++ 部分创建一个 DLL 并通过 JNA 访问它。由于我在 c++ 方面是一个完全的初学者,我想我从一个最小的基础开始,然后从那里继续工作。但是,我什至无法运行这些最小示例。这是我所做的:

我使用Visual Studio的文档来创建我的DLL(在这里找到:https://msdn.microsoft.com/de-de/library/ms235636.aspx)

你在那里做的是你定义一个标题

// MathFuncsDll.h
#ifdef MATHFUNCSDLL_EXPORTS
#define MATHFUNCSDLL_API __declspec(dllexport) 
#else
#define MATHFUNCSDLL_API __declspec(dllimport) 
#endif
namespace MathFuncs
{
 // This class is exported from the MathFuncsDll.dll
 class MyMathFuncs
 {
 public: 
    // Returns a + b
    static MATHFUNCSDLL_API double Add(double a, double b); 
 };
}

和.cpp文件

// MathFuncsDll.cpp : Defines the exported functions for the DLL application.
#include "stdafx.h"
#include "MathFuncsDll.h"
#include <stdexcept>
using namespace std;
namespace MathFuncs
{
 double MyMathFuncs::Add(double a, double b)
 {
    return a + b;
 }
}

然后将其构建到 DLL 中。到目前为止,这没有错误。然后,我继续编写一个小的Java程序来通过JNA访问这个DLL,再次坚持JNA文档:

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
/** Simple example of JNA interface mapping and usage. */
public class HelloWorld {
  // This is the standard, stable way of mapping, which supports extensive
  // customization and mapping of Java to native types.
  public interface CLibrary extends Library {
      CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "zChaffDLL" : "c"), CLibrary.class);
      double Add(double a, double b);
  }
  public static void main(String[] args) {
      CLibrary.INSTANCE.Add(5d, 3d);
  }
}

运行此操作会导致此错误:线程"main"中的异常 java.lang.UnsatisfiedLinkError: 查找函数"Add"时出错:找不到指定的过程。

我捣鼓了一下,但无法解决问题。在这一点上,我几乎迷失了,因为我认为自己无法构建一个更简单的例子 - 所以任何帮助或指示将不胜感激。

C++"

mangles"根据编译器的突发奇想导出名称。 例如,"void main(argc, argv)"可能显示为"_Vmain_IPP@xyzzy"。

运行取决于.exe DLL 以查看导出的名称的外观。 代码中的extern "C"将阻止C++修改导出的函数名称。

JNA 可以很好地处理静态函数;JNAerator 会自动容纳一些额外的重整,但如果你想将C++类映射到 Java 类上,你最好使用 SWIG 之类的东西。

相关文章: