Android

android 에서 NDK로 구조체 보내기

술퍼 2019. 2. 22. 10:05

java

-----------------

package woenho.ns;



public class MainActivity extends AppCompatActivity {

// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

CTest test = new CTest();

// Example of a call to a native method
TextView tv = findViewById(R.id.sample_text);
tv.setText(stringFromHello(test,"Example", 777));

}

/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromHello(CTest test,String strTitle, int nLuck);



public class CTest{
public CTest(){

serial = 99;
strData = "test data";
}
public long serial;
public String strData ;
}

}


===================

NDK

----------------

extern "C" JNIEXPORT jstring JNICALL
Java_woenho_ns_MainActivity_stringFromHello(
JNIEnv *env, jobject instance,
jobject test, jstring strTitle, jint nLuck ) {

jclass jClass;
jClass = env->GetObjectClass(test);

jfieldID fid;
fid = env->GetFieldID(jClass, "serial", "J");

jlong serial = 0;
if( fid != NULL )
serial = env->GetLongField(test, fid);

char szMsg[512] = {0,};
fid = env->GetFieldID(jClass, "strData", "Ljava/lang/String;");
if( fid != NULL ) {
jstring jstr = (jstring) env->GetObjectField(test, fid);
if (jstr != NULL) {
const char *pcName = env->GetStringUTFChars(jstr, NULL);
strcpy(szMsg, pcName);
// ReleaseStringUTFChars 반드시 해준다.
env->ReleaseStringUTFChars(jstr, pcName);
}
}

char hello[512]={0,};
char title[512]={0,};

const char *szParam = env->GetStringUTFChars(strTitle, NULL);
strcpy( title, szParam);
env->ReleaseStringUTFChars(strTitle, szParam);

sprintf( hello, "%s(%lld:%s) -> %d", title, serial, szMsg, nLuck);

return env->NewStringUTF(hello);
}


======================

Java VM Type Signatures

---------------------------------------------

TYPE SIGNATURE JAVA TYPE

---------------------------------------------

Z -> boolean

B -> byte

C -> char

S -> short

I -> int

J -> long

F -> float

D -> double

L fully-qualified-class ; -> fully-qualified-class --> string이 대표적

[ type -> type[]

( arg-types ) ret-type         -> method type

---------------------------------------------

For example, the Java method:

---------------------------------------------

long f (int n, String s, int[] arr); ->(ILjava/lang/String;[I)J   ====> ( "I", "Ljava/lang/String;", "[I", ) "J"


============
ref
==================
LPackage/StructType;