无法使用JNI从java调用C++的成员函数

Dil*_*ung 5 c++ java java-native-interface interop

我按照下面给出的指令 从Java中调用c函数调用c函数, 然后我就可以调用C++函数了.但是现在我想从Java调用C++类的成员函数.为了清楚地描述它,我引用了下面的场景.

JAVA.有一个名为HelloWorld.java的类,它有一个名为print() Now的本机函数,使用Java的JNI我已经为HelloWorld创建了等效的头文件.之后我在HelloWorld.cpp中编写了这个头文件的实现

现在从"HelloWorld.cpp"我想调用"rectangle.cpp"的成员函数,我已经为其创建了"rectangle"对象并调用了它的相应函数.但是在编译代码时,它会给我一个名为"未解析的外部符号"的错误.相反,当我在rectangle.h中的相应头文件"rectangle.cpp"中编写所有实现时,代码编译得很好,它给了我想要的结果.我的问题,没有办法,然后我可以调用.cpp类的成员函数而不是它相应的头文件函数.

以下是代码片段::

HelloWorld.java

 class HelloWorld {

 private native void print();
 private native void multiply();


 public static void main(String[] args) {
     new HelloWorld().print();
     new HelloWorld().multiply();

 }

 static {
     System.loadLibrary("HelloWorld");
 }  }
Run Code Online (Sandbox Code Playgroud)

HelloWorld.h

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

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    print
 * Signature: ()V
 */

JNIEXPORT void JNICALL Java_HelloWorld_print
  (JNIEnv *, jobject);

/*
 * Class:     HelloWorld
 * Method:    multiply
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_multiply
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif
Run Code Online (Sandbox Code Playgroud)

HelloWorld.cpp

 #include <jni.h>
 #include <stdio.h>
 #include "rectangle.h"
 #include "HelloWorld.h"



JNIEXPORT void JNICALL   Java_HelloWorld_print(JNIEnv *env, jobject
obj)  
{
//     printf("Hello World!dfdfdfdf\n");
//     return;  

Rectangle rectangle;
rectangle.set_values(3,4);
printf("Area of Rectangle %d", rectangle.get_values());

} 
JNIEXPORT void JNICALL Java_HelloWorld_multiply
  (JNIEnv *, jobject)
{
//printf("dila ");
}
Run Code Online (Sandbox Code Playgroud)

rectangle.h

#ifndef GUARD_SNAKE_H
#define GUARD_SNAKE_H
class Rectangle{
  public:
    Rectangle(void);
 //   ~Rectangle(); 


    void  set_values(int x,int y);
    int get_values();   
  private:
  int width;
  int height;


};

#endif
Run Code Online (Sandbox Code Playgroud)

rectangle.cpp

// classes example
#include "rectangle.h"
Rectangle::Rectangle(void)
{
}
void  Rectangle::set_values(int x, int y) 
{
  width = x;
  height = y;
}
int Rectangle::get_values()
{
return width*height;    
}
Run Code Online (Sandbox Code Playgroud)

与上述代码相关的问题:当我在其头文件"rectangle.h"中编写了"矩形"的所有实现时,它给了我想要的结果.问题是在"HelloWorld.cpp"文件上创建的"矩形"对象不是指"rectangle.cpp".这就是为什么当我编译并运行它时,它给了我"未解析的外部符号"异常,这意味着编译器或调试器无法找到"rectangel.h"文件中定义的函数的实现.有没有办法解决这个问题..请帮助.

Oo.*_*.oO 0

如果您想使用多个来源,请确保:

  • 要么将所有内容放入单个库中,要么
  • 确保创建多个库并确保正确链接它们。

您可以在这里找到非常简单的示例:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo021 https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo023