the-mac / AndroidJniHelpers

Tools for writing secure Android/JNI code, based upon Spotify's Jni Helpers Library
http://on.fb.me/1MIc51o
MIT License
37 stars 5 forks source link

Map native field to java static field? #4

Closed netstu closed 6 years ago

netstu commented 6 years ago

example;

class StaticClass { public static int a; public static String b; }

how to wrtie cpp file, to set value to java class?

cdm2012 commented 6 years ago

I want to make sure I understand your question.

You want to create a C++ class that can make changes to Java Static Members?

To answer your questions, I need to know if you are using the AndroidJniHelpers library project (in Android), or just in Java (in the Spotify project), or do you want to use no library project (just C++ and Java)?

I believe I have a solution for you, but I just want to make sure I understand your question?

netstu commented 6 years ago

@cdm2012 hello, thx

i use this library in my android.

i see all the test example, java and cpp file.

in them example, only java object <--> cpp object

but i want cpp data to java static field, not object filed

in the JavaClass.cpp,has SettoJava and toJavaObject, but this two method only object data convert, i want to add cpp data to Java class static fileld

netstu commented 6 years ago

i hava the class like this ,

class JavaTest {

public static String astr;
public static String bstr;

public static void amethod() {}

public static String bmethod() {}

}

i want to use native to write.

cdm2012 commented 6 years ago

I had a problem similar to yours and I decided to use a special native helper method to assist with assigning static variables. I found out that all JNI code first loads inside the JNI_OnLoad method, but the Java static references load as soon as they are used (sometimes before JNI_OnLoad happens). In the case of the demo project, its JNI_OnLoad can be found here.

My solution to this loading problem was to call to the custom getS helper method to load my static members. Take a look at the MainIntentService class for an example. Here is a snippet from that class and the AndroidJniApp.getS helper method that is provided for you to use in your other projects:

public class MainIntentService extends IntentService {
    static {
        Log.d(MainIntentService.class.getName(), "Called static {...} successfully");
        // SET AUTHORITY: us.the.mac.demo.library.androidjni.provider
    }
    public static final String PARAM_IN_MSG = "imsg";
    public static final String WELCOME_MESSAGE = AndroidJniApp.getS(0);
    ...
}