Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.loadLibrary() not working in some instances

I am making a cocos2d-x game and I was experiencing some weird behavior im not sure if its normal or whats going on but this is whats happening, so the AppActivity.java class extends Cocos2dxActivity.java class. I did not have to call System.loadLibrary("MyGame"); in my AppActivity.java class since it is being called in Cocos2dxActivity.java. But this is what happens if I do a normal declaration like this

private native String invokeNativeString();

everything works fine, but then I try to declare this directly underneath and I receive this error

String ami = new String(invokeNativeString());

And got errors:

05-01 09:11:27.250 10135-10135/com.izzyjmachado.spaceball E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.izzyjmachado.spaceball, PID: 10135
        java.lang.UnsatisfiedLinkError: No implementation found for java.lang.String org.cocos2dx.cpp.AppActivity.invokeNativeString() (tried Java_org_cocos2dx_cpp_AppActivity_invokeNativeString and Java_org_cocos2dx_cpp_AppActivity_invokeNativeString__)

Why is it working when I declare a normal native string but when I use the method inside the declaration of a string its not finding the method ?

I was able to resolve this by calling this in my AppActivity class but I feel like it should be working with out having to call loadLibrary in my appActivity class since its already being called in Cocos2dxActivity and appActivity extends Cocos2dxActivity ? thanks to any help you guys can give me

static {
    System.loadLibrary("MyGame");
}
like image 561
isJulian00 Avatar asked Jun 05 '26 18:06

isJulian00


2 Answers

That's because your activity calls super.onCreate() early in its onCreate(). Just to make it clear: This is how it should be called, you made no mistake.

But. Cocos2dxActivity authors chose to load the native library during onCreate(). They had a good reason to make this decision: it allowed them to extract android.app.lib_name from your package, and this way to choose the correct library.

The JNI tutorials usually recommend to load the native libraries in static {} block. The latter is a safer practice (e.g. it resolves your problem with field initialization), but it has its own drawbacks, too.

The bottom line, you can move initialization of the ami field into AppActivity.onCreate(), if you like this way, or you can use the static block in your AppActivity, if you prefer. The end user will not really notice the difference.

like image 68
Alex Cohn Avatar answered Jun 07 '26 06:06

Alex Cohn


It seems you tried to call native function while native library is not yet loaded.

like image 21
Dmytro Avatar answered Jun 07 '26 08:06

Dmytro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!