Prasad
Prasad

Reputation: 1375

Calling C function in java class of android NDK

I have one function of c file(ht_NDK.c) for my NDK application like this,

int heatcon_readtemperature(char* temperature)
   {
    int nret,ok;
    char cmd[3]={'d',0x0d, 0x0a};
    struct pollfd pfd;
    static int i=0;
        char read_temp[255]="banagalore";
    i++;
    memcpy(temperature, &read_temp, i);
    if(i==10)
    i=0;
    return nret;
    }

In another c file(second.c) I am calling above function like below,

jstring
Java_com_example_ndk_ReadData_readData( JNIEnv*  env,
                                      jobject this,jstring printMatter, jint j)
{
   char sz[55] = {0};
   return((*env)->NewStringUTF(env,  heatcon_readtemperature(sz)));       

} 

the above function calling in my java class(ReadData.java) like below

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_data);       


        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                ReadData rd = new ReadData();
                String n = rd.readData();
                Log.i("NDK", "msg" +n);         
            }
        });

       }

   static
    {
        System.loadLibrary("ht");
        System.out.println("loded library");
    }  


      public native int[] readData();

    }    
}

So that Whenever I press button the value should print on console, Everything is fine but its printing null value. How to call char data type in java class. I think I am missing some thing. How to resolve this?

Upvotes: 2

Views: 3614

Answers (1)

Kris Van Bael
Kris Van Bael

Reputation: 2862

Your first function outputs two things:

  • it returns an int value (which is uninitialized, you need to fix that)
  • it modifies the char* argument.

When you make the java string (NewStringUTF) you pass the int return value. You probably intended to pass the char* value instead:

char sz[55] = {0};    
heatcon_readtemperature(sz);
return (env*)->NewStringUTF(env, sz);

Upvotes: 3

Related Questions