Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How put std::vector of ints into jintArray?  RSS feed

 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a vector of ints that i want to put into a jintArray. How do I do this?

When I tried the below code, it didn't work but instead when i printed out the int values on the java side, they were all messed up.



This returns weird values. What am I doing wrong?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The address of the vector<int> is not going to be the address of the ints; vector<int> is a class which contains several member variables, of which the array of ints is only one.

It's been a few years since I was an STL hacker, but I believe you need to get a forward iterator from the vector<int>, and it will be a pointer to the first int -- i.e., case intVector.begin() to a jint*.

Even that isn't actually technically guaranteed, AFAIK; but it should work on any actual implementation.
 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
The address of the vector<int> is not going to be the address of the ints; vector<int> is a class which contains several member variables, of which the array of ints is only one.

It's been a few years since I was an STL hacker, but I believe you need to get a forward iterator from the vector<int>, and it will be a pointer to the first int -- i.e., case intVector.begin() to a jint*.

Even that isn't actually technically guaranteed, AFAIK; but it should work on any actual implementation.


Thanks for the reply!

I figured it out, my code was simply missing the reference to the first spot. Since the standards (only since 2003) for std::vector state that the items MUST be kept in sequential/contiguous order in memory space, you can point to the first one and be certain you're getting the array. So if I change my code to be:



it will work! I was just missing the "[0]" (whoops ). I could also use ".begin()", is there any reason that's a better choice than [0]? I think it might throw an exception if 0 is an invalid index.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dan Bizman:
I could also use ".begin()", is there any reason that's a better choice than [0]? I think it might throw an exception if 0 is an invalid index.


I'm not sure begin() works any better for zero-length arrays.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!