是否可以在android中调用嵌套的本机函数?

时间:2014-05-12 05:32:10

标签: android java-native-interface native

所以我有一个c ++类,它有很多函数,它们是每个函数内的嵌套调用(请看下面的示例)。

 void function1(){

      function2();
      function3();

 }

 void function2(){

      //Some implementation of function 2 here

 }


 void function2(){

      //Some implementation of function 3 here

 }

我现在想编写一个JNI包装器来调用function1,我的问题是我是否必须为所有3个函数编写JNI包装器,或者如果我为function1编写JNI就足够了?

另外,如果我必须为所有函数编写JNI包装器,那么函数1是否可以调用function2&功能3?因为在根据JNI修改函数名后,我该如何调用它们?

我的JNI示例:

    JNIEXPORT void JNICALL Java_com_example_MainActivity_function1(){

              //How do I call other functions here?
    }

任何指针都会受到赞赏。

编辑:

请求的C ++类:

 void Controller::initialize(InitData Data)
 {
// Create all managers

Log.d("Log","came in logd");
readConfig(Data);
createManagers();

// Create UserInterface

createUserInterface();

// Initialize all managers

initializeManagers(); 

// Initialize all modules

initializeModules(Data);

// Initialize loggers



  m_sessionModule->waitForSessionResponse();

 }

被调用的其余函数在同一个类中定义

1 个答案:

答案 0 :(得分:0)

  1. 为了在JNI中调用C ++类的方法,必须已经创建了该类的对象(如果它不是静态方法)。
  2. 您只需要为可以从Java代码调用的方法创建JNI包装器。
  3. 实施例

    C ++类:

    class Controller
    {
    public:
      void function1()
      {
        function2();
        function3();
      }
    
      void function2(){}
      void function3(){}
    }
    

    JNI方法:

    JNIEXPORT void JNICALL Java_com_example_MainActivity_function1()
    {
      //getControllerInstance() must to return the already created 
      //instance of the class.
      Controller* controller = getControllerInstance();
    
      if(controller != nullptr)
        controller->function1();
    }
    
    //If you want to call function2() method from Java.
    JNIEXPORT void JNICALL Java_com_example_MainActivity_function2()
    {
      //getControllerInstance() must to return the already created 
      //instance of the class.
      Controller* controller = getControllerInstance();
    
      if(controller != nullptr)
        controller->function2();
    }
    

    P.S。上面的代码就是一个例子,它不是代码。

相关问题