Call c++ function from java?

Hi!

I am creating an android game and have made a popup with two buttons in my AppActivity.java and I want one of the buttons to call one of my cpp functions… How?

Thanks!

1 Like

You should use native functions in java to call c++ part.

Java:

package com.mypackage;
public class MyClass {
     public native void myCppFunction();
}

Now if call this function - c++ code will be executed.

C++: (function name is important, file name/location not important)

#include <jni.h>

#ifdef __cplusplus
extern "C" {
#endif
    void Java_com_mypackage_MyClass_myCppFunction(JNIEnv *env, jobject thiz) {
      //it corresponds to java native function
    }
    
#ifdef __cplusplus
}
#endif

Actually you should read some guide about it, but here few notes:

1 Like

Thanks! Here is my code:
In wrapper.cpp I have included this:

#if(CC_PLATFORM_TARGET == CC_PLATFORM_ANDROID)
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#endif

…
Then I implemented this code:

#ifdef __cplusplus
extern "C" {
#endif
    void Java_org_cocos2dx_AppActivity_myCppFunction(JNIEnv *env, jobject thiz) {
     CCLOG("It works!");
    }

#ifdef __cplusplus
}
#endif

And I did nothing to the header.

So in my AppActivity.java I did this:

package org.cocos2dx.cpp;


import sonar.systems.framework.SonarFrameworkActivity;


import android.util.Log;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.app.AlertDialog;



public class AppActivity extends SonarFrameworkActivity 
{
	private static AppActivity app = null;
    public static String filename = "sharedData";
    public static SharedPreferences someData;
    public native void myCppFunction();
 static int currency;

    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);
    
        app = this;
        //Set the sharedPreferences
        someData = getSharedPreferences(filename, 0);
        //Check network status
        myCppFunction();
 
        
        
	}

But after I did this the app crashes every time.
Think this is the issue:

How to fix? Thanks you so much!

1 Like

Have you compiled your cpp file - added it to android.mk?

Edit.
Seems like you missed part of package name - org.cocos2dx.cpp
Function should be named:

Java_org_cocos2dx_cpp_AppActivity_myCppFunction
1 Like

Thanks It is working now! <3