Home > Net >  Get wrong value from int* to JintArray in jni
Get wrong value from int* to JintArray in jni

Time:05-17

I have a c function int* GenerateIntArray()

it will generate a int array like [0,8,28,108,0,3] and return by Int*

int* GenerateIntArray(){ 
int rtn[6]={0,8,28,108,0,3};
return rtn;
}

in my jni layer : fun getIntArrayFromJNI:JIntArray

I do this for get Int* from C Lib

jintArray rtn = env->NewIntArray(6);
int *temp = C_GetINTArrayData();
env->SetIntArrayRegion(rtn, 0, 6, temp);
return rtn; 

and convert it to IntArray

but in Android Layer: fun getIntArrInAndroid():IntArray

var result=getIntArrayFromJNI()

I check the data list it show [-214587424,119,0,0,205189680,-1275068295]

is somewhere wrong to convert Int array?

CodePudding user response:

Since your problem seem to coming from your GenerateIntArray function, returning a pointer to local variable (which is not a good idea at all), I suggest you rewrite the function in more suitable way:

void GenerateIntArray(int *buffer, size_t size) 
{
   for(size_t i = 0; i < size;   i) 
     // do something with your buffer...
}

You then should call the GenerateIntArray with a valid pointer like this :

int array[256];

GenerateIntArray(array, 256);

or using dynamically allocated buffer, like that :

int* buffer = (int*)malloc(256 * sizeof(int));

GenerateIntArray(buffer, 256);

Alternatively, in C fashion using vector standard container as suggested by @Michael in comments :

void GenerateIntArray(std::vector<int>& array) 
{
   // do something with your array...
}

With the following usage:

std::vector<int> my_array;

GenerateIntArray(my_array);

CodePudding user response:

When you want to do that in this way, you can change your void GenerateIntArray() code to:

int* GenerateIntArray()
{ 
  static int rtn[6]={0,8,28,108,0,3};
  return rtn;
}

Because, the int array is allocated on the stack and will be disappear when the function returns.

  • Related