【问题标题】:JNI - make an instance of another C++ classJNI - 创建另一个 C++ 类的实例
【发布时间】:2014-12-12 07:47:29
【问题描述】:

我有一个旧应用程序 (C++),我想通过 JNI 使用 java 调用它。 所以我阅读了一些教程,基础知识(从 Java 调用 C++ 中的方法)效果很好。

但现在我的问题是我想在方法中实例化另一个 C++ 对象,该对象由 JNI 使用。这主要是不可能的还是有什么办法可以做到这一点?

解释:

这是我的 Java 类 helloworld.java,它调用本地方法 'callnative()'

public class helloworld{
  private native void callnative();

  public static void main(String[] args){
    new helloworld().callnative();

  }

  static {
     System.loadLibrary("helloworld");
  }
}

这是本地方法 java_helloworld_callnative(..)

#include <jni.h>
#include <stdio.h>
#include "helloworld.h"
#include "hellouniverse.h"

JNIEXPORT void JNICALL Java_helloworld_callnative(JNIEnv *env,
                                              jobject obj)
{
  printf("HelloWorld\n");
  hellouniverse *h = new hellouniverse();
  h->printHelloUniverse();
  return;
}

这是类hellouniverse

#include "hellouniverse.h"
#include <stdio.h>
#include <string>

using namespace std;

hellouniverse::hellouniverse(){ 
}

void hellouniverse::printHelloUniverse(){
  printf("HelloUniverse!!\n");
}

我编译了 helloworld.cpp:

g++ -fPIC -shared -I$JAVA_PATH/include -I$JAVA_PATH/include/linux/ -o libhelloworld.so hellworld.cpp

和 hellouniverse.cpp 与:

g++ -c -o hellouniverse.o hellouniverse.cpp

当我运行 java helloworld 时,输出是:

你好世界 java:符号查找错误:$./libhelloworld.so:未定义符号:_ZN13hellouniverseC1Ev

我希望你能帮我解决我的问题:-)

【问题讨论】:

    标签: java c++ object java-native-interface


    【解决方案1】:

    您必须将hellouniverse 的东西链接到库中。例如

    g++ -fPIC -shared -I$JAVA_PATH/include -I$JAVA_PATH/include/linux/ -o libhelloworld.so hellworld.cpp hellouniverse.cpp
    

    或者

    g++ -fPIC -I $JAVA_PATH/include -I$JAVA_PATH/include/linux -c helloworld.cpp
    g++ -fPIC -I $JAVA_PATH/include -I$JAVA_PATH/include/linux -c hellouniverse.cpp
    g++ -fPIC -shared -o libhelloworld.so helloworld.o hellouniverse.o
    

    考虑使用 Makefile 自动执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 2023-04-02
      • 2018-11-02
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      相关资源
      最近更新 更多