Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Android NDK and C++

I got the sample HelloJni project working, which uses a C file for the native code. I have not been able to get any simple examples working with C++. Take the following JNI code:

#include <jni.h>
#include <string.h>

JNIEXPORT void JNICALL Java_com_test_testActivity_doSomething(JNIEnv * env, jobject obj)
{

}

If I have the code in a .c file, it works fine. If I change the extension to .cpp it compiles fine, but blows up when running (force closes). Since the library and method signature is the same either way, I don't suspect the problem being on the Java side.

like image 917
Philip Avatar asked Mar 13 '11 20:03

Philip


2 Answers

You might need to surround your code with an extern "C" block:

extern "C" {

    JNIEXPORT ...

}

You should be able to make a version that will work in both C and C++ by wrapping the extern block in #if:

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT ...

#ifdef __cplusplus
}
#endif
like image 195
Matthew Willis Avatar answered Oct 04 '22 07:10

Matthew Willis


Java_com_test_testActivity_doSomething will need to be extern "C".

like image 38
Logan Capaldo Avatar answered Oct 04 '22 06:10

Logan Capaldo