I am trying to use java to pass some command line arguments to c++ code.

Alexander Krapf

Your first problem is easily explained:

GetStringUTFChars returns a pointer that is only valid until you call ReleaseStringUTFChars. Once you've called the latter method, the memory that was used to hold the bytes may get recycled which is why you get garbage.

You had the right idea trying to make a copy, but you need to be careful when doing that. Your array is only an array of pointers and does not have any buffers allocated to hold the strings. If you knew the maximum length of the strings that are being passed in, you could simply change your code to

  char    argv[32][MAX_LENGTH];
  ...
  strcpy( argv[i], str );
and that should work fine. If you do not know the maximum length or do not want to waste a lot of space, you should dynamically allocate the strings based on the string length

  char *  argv[32];
  ...
  argv[ i ] = new char[ strlen( str ) + 1 ];
  strcpy( argv[i], str );
You are then of course responsible for cleaning up behind yourself.

Beyond your immediate problem, you also need to be aware that what you get is a UTF string. This means that the ASCII characters will be fine, but any characters over 127 (accented characters, umlauts, etc.) will be represented in UTF (multiple bytes) and not in the form that you want. There are some excellent books on JNI that might help you ("The Java Native Interface" by Sheng Liang among them).

You might also be interested in investigating our JunC++ion tool (http://www.codemesh.com), a tool that solves your problem and many others beside it by making Java interoperate extremely well with C++ (in the interest of disclosure: I am a principal at Codemesh).

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact