Passing (byref) String from Java to C++ via JNI

I wish to pass a string to a C++ Dll as a parameter in a function. The problem is that I don't know howto receive back the data after it is filled in the C++ dll. I am trying to do what is called passing parameters by reference.
Java Code:
public class ABKeyBoard {
public native long leerBanda(int pista, String datos);
public static void main(String[] args) {
String datos=new String();
System.loadLibrary("ABKeyBoard");
new ABKeyBoard().leerBanda(1,datos);
System.out.println(datos); //the content of datos here is empty.
C++ Code:
Java_ABKeyBoard_leerBanda(JNIEnv *env, jobject obj,jint pista, jstring datos)
     char buffer[2024];
     memset(buffer,     0x00,     sizeof(buffer));
     strcpy(buffer, "xxxx");
     datos = env->NewStringUTF(buffer);
return;
Thanks for your help.

In java every parameter are always passed by value.
The datos parameter is a local copy of the string
reference you pass to the method.This is wrong. The String passed to the native method is the same String object you use in Java. Although everything is passed by value in Java, what is actually passed by value is the reference to the String. This means that you can modify the object you pass, but you are not allowed to change the reference to point to a totally different object. That is where the problem is coming in.
The trouble is that it is illegal to modify a String, even from native code. If you need to make changes in-place to the text, pass an array of chars (if your native code uses Unicode), an array of bytes (if it uses normal 8-bit characters) or a StringBuffer. You can legally modify any of these data structures with the new data. But the StringBuffer object is the only one whose length can be changed after it is created. Unfortunately it is also the hardest to use from JNI.
Generally I think you should always pass arrays of bytes/chars to native code instead of Strings when possible. They can be modified in place, and you can use String's methods to get a byte-array in the platform's proper encoding. Using the GetStringUTFChars method is problematic because UTF only maps directly onto ASCII in the case of characters which are in the set of 7-bit ASCII characters. Your code will do wrong things if your String happens to contain some other character, unless your native code expects UTF format strings.
The good news is that C(++) functions which return results in their arguments do not ordinarily change the length. So you should be able to allocate a byte[] or char[] ahead of time of the appropriate size (don't forget to add the trailing null, which is not a component of Java strings). I think byte[] or char[] is the best answer because you can easily map those onto C-style arrays with Get[Primitive]ArrayRegion; the return of that is suitable for passing directly to native code, as long as you have remembered the null-terminator. For instance you could do (*env)->GetByteArrayRegion(env, javaArray, 0, arrayLength, CArray) and then your CArray would be changed to point at the contents of the javaArray (note: it does not copy data into CArray, it changes CArray to point at the array contents, so do not allocate memory for CArray first). Then when you do ReleaseByteArrayRegion the results will be propagated back to Java.

Similar Messages

  • Passing a String from Java to Javascript

    Does anybody know how to pass a string from Java class to Javascript ? Can it be done?

    If you are talking in terms of web terminology...
    People do intialization of page in the following way.
    var java_script_variable = <%=String_variable%>

  • Re: Passing a string from Java class to JSP

    How can I pass a string from a function within my bean class to my JSP page?
    I would like to pass something like this with the necessary params filled in:
    String myString ="Successful <b>" + Sales.getActionType() + "</b> was made on <b>" + (new Date()).toString();
    The ActionType will be either a BUY or SELL and the current date need to be added in.
    Thank you in advance!

    SOLVED THE PROBLEM!!!

  • Is it possible to pass a string from an applet to the web site?

    Hi, everybody!
    Is it possible to pass a String from an applet to a web site (as a field value in a form, an ASP variable, or anything else). Basically, I have a pretty large String that is being edited by an applet. When a user clicks on the submit button, a different page will show up which has to display the modified string. The String is pretty large so it doesn't fit into the URL variable.
    Please, help!
    Thank you so much!

    Why do you want to do this in Java?
    Javascript is the correct language for these type of situations.
    for instance:
    in the head of your html document:
    <script language=javascript type="text/javascript">
    createWindow(form){
    if(form.text.value!=""){
    newDoc = new document
    newDoc.write(form.text.value)
    newWin = window.open(document,'newWin','width=200;height=150')
    </script>
    in the body:
    <form onSubmit="createWindow(this)">
    <p>
    Enter a String:<input type=text size=30 name="text">
    </p><p>
    <input type=submit value="submit"> 
    <input type=reset value="reset">
    </p>
    </form>

  • Passing Tables back from Java Stored Procedures

    Thomas Kyte has written (in reference to
    trying to pass an array back from a stored
    function call):
    You can do one of two things (and both require the use of
    objects). You cannot use PLSQL table types as JDBC cannot bind to
    this type -- we must use OBJECT Types.
    [snip]
    Another way is to use a result set and "select * from
    plsql_function". It could look like this:
    ops$tkyte@8i> create or replace type myTableType as table of
    varchar2 (64);
    2 /
    Type created.
    ops$tkyte@8i>
    ops$tkyte@8i>
    ops$tkyte@8i> create or replace
    2 function demo_proc2( p_rows_to_make_up in number )
    3 return myTableType
    4 as
    5 l_data myTableType := myTableType();
    6 begin
    7 for i in 1 .. p_rows_to_make_up
    8 loop
    9 l_data.extend;
    10 l_data(i) := 'Made up row ' &#0124; &#0124; i;
    11 end loop;
    12 return l_data;
    13 end;
    14 /
    Function created.
    ops$tkyte@8i>
    ops$tkyte@8i> select *
    2 from the ( select cast( demo_proc2(5) as mytableType )
    3 from dual );
    COLUMN_VALUE
    Made up row 1
    Made up row 2
    Made up row 3
    Made up row 4 [Image]
    Made up row 5
    So, your JDBC program would just run the query to get the data.
    If the function "demo_proc2" cannot be called from SQL for
    whatever reason (eg: it calls an impure function in another piece
    of code or it itself tries to modify the database via an insert
    or whatever), you'll just make a package like:
    ops$tkyte@8i> create or replace package my_pkg
    2 as
    3
    4 procedure Make_up_the_data( p_rows_to_make_up in
    number ); 5 function Get_The_Data return myTableType;
    6 end;
    7 /
    Package created.
    ops$tkyte@8i>
    ops$tkyte@8i> create or replace package body my_pkg
    2 as
    3
    4 g_data myTableType;
    5
    6 procedure Make_up_the_data( p_rows_to_make_up in number )
    7 as
    8 begin
    9 g_data := myTableType();
    10 for i in 1 .. p_rows_to_make_up
    11 loop
    12 g_data.extend;
    13 g_data(i) := 'Made up row ' &#0124; &#0124; i;
    14 end loop;
    15 end;
    16
    17
    18 function get_the_data return myTableType
    19 is
    20 begin
    21 return g_data;
    22 end;
    23
    24 end;
    25 /
    Package body created.
    ops$tkyte@8i>
    ops$tkyte@8i> exec my_pkg.make_up_the_data( 3 );
    PL/SQL procedure successfully completed.
    ops$tkyte@8i>
    ops$tkyte@8i> select *
    2 from the ( select cast( my_pkg.get_the_data as mytableType
    ) 3 from dual );
    COLUMN_VALUE
    Made up row 1
    Made up row 2
    Made up row 3
    And you'll call the procedure followed by a query to get the
    data...
    I have tried this, and it works perfectly.
    My question, is what does the wrapper look
    like if the stored function is written
    in java instead of PL/SQL? My experiments
    with putting the function in java have been
    dismal failures. (I supposed I should also
    ask how the java stored procedure might
    look also, as I suppose that could be where
    I have been having a problem)
    null

    Thanks for the response Avi, but I think I need to clarify my question. The articles referenced in your link tended to describe using PL/SQL ref cursors in Java stored procedures and also the desire to pass ref cursors from Java to PL/SQL programs. Unfortunately, what I am looking to do is the opposite.
    We currently have several Java stored procedures that are accessed via select statements that have become a performance bottleneck in our system. Originally the business requirements were such that only a small number of rows were ever selected and passed into the Java stored procedures. Well, business requirements have changed and now thousands and potentially tens of thousands of rows can be passed in. We benchmarked Java stored procedures vs. PL/SQL stored procedures being accessed via a select statement and PL/SQL had far better performance and scaleable. So, our thought is by decouple the persistence logic into PL/SQL and keeping the business logic in Java stored procedures we can increase performance without having to do a major rewrite of the existing code. This leads to the current problem.
    What we currently do is select into a Java stored procedure which has many database access calls. What we would like to do is select against a PL/SQL stored procedure to aggregate the data and then pass that data via a ref cursor (or whatever structure is acceptable) to a Java stored procedure. This would save us a significant amount of work since the current Java stored procedures would simple need to be changed to not make database calls since the data would be handed to them.
    Is there a way to send a ref cursor from PL/SQL as an input parameter to a Java stored procedure? My call would potentially look like this:
    SELECT java_stored_proc(pl/sql_stored_proc(col_id))
    FROM table_of_5000_rows;
    Sorry for the lengthy post.

  • Example of passing String Array from java to C using JNI

    hi all
    i searched net for passing string array from java to C but i dont get anything relevent
    i have
    class stu
    int rollno
    string name
    String [] sub
    i want to pass all as String array from java to C and access it C side

    1. Code it as though it were being passed to another method written in java.
    2. Redefine the method implementation to say "native".
    3. Run jnih to generate a C ".h" file. You will see that the string array
    is passed into C as a jobject, which can be cast to a JNI array.
    4. Write the C code to implement the method and meet the interface
    in the generated .h file.

  • Passing an array from Java to Pl/SQL Procdures

    I am relatively new to the Java world and I am unable to pass back an array from Java back to the calling PL/SQL procedure. I have read many of the posts that deal with this issue and in specificly have viewed Ask Tom. My main issue is trying to get the data types matched up. I am able to return varchar2, numbers, and the like, but an array of filenames is not happening. I have tried a variety of "types" but unable to accomplish the task. Please help.
    I have my Java class basically defined as:
    public static oracle.sql.ARRAY[] getCollection(String directory)
                   throws SQLException
    { // provide a directory and get a listing of files
    File path = new File( directory );
    String[] list = path.list();
    return list;
    SQL Type and PL/SQL Procedure is:
    CREATE OR REPLACE TYPE PTO_FILE IS TABLE OF VARCHAR2(100);
    create or replace function get_dir_collection( p_directory in varchar2 ) RETURN PTO_FILE
         as language java
    name 'DirCollection.getCollection( java.lang.String ) return oracle.sql.ARRAY[]';
    /

    I know that it is not an ARRAY. It is however an "array" and I am attempting to map Java's String[][ to some "object" on the oracle side.  I have looked at the link you sited and was not able to find the data mapping.  I have found that mapping data types between different "languages" is some of the most difficult aspects of working with multiple languages.
    Any suggestions? Thanks

  • Why returning string from java stored function failed ?

    I created java stored function: it's doing http post, parsing xml from http reply, and returning string result.
    Sometimes, it doesn't return any value. What can be a reason ?
    The high level procedure, has following form:
    class SBE {
    public static String call(String arg0) {
    SBE sbe=new SBE("d:\\oracle\\ora81\\network\\log\\SBE.log");
    String result=SBEParser.go(sbe.sendRequest(arg0, ""), sbe.logger);
    sbe.logger.log(result);
    sbe.logger.log("Finish SBE intetraction");
    return result;
    PLSQL wrapper has a simple form:
    create or replace package PG_SBE as
    function CALL(arg0 in varchar2) return varchar2;
    end;
    create or replace package body PG_SBE as
    function CALL(arg0 varchar2) return varchar2 as language java name 'SBE.call(java.lang.String) return java.lang.String';
    end;
    In log file ("d:\\oracle\\ora81\\network\\log\\SBE.log"), I can find message :
    "Finish SBE intetraction"
    but query:
    select pg_sbe.call("any argument") from dual;
    doesn't finish.
    What can be a reason ? What can I do to trace stage of convertion java string to varchar ?
    Please help me...
    Marek

    This comes up periodically. It just isn't possible using that type of approach. Probably the best you could do is the create an ADT (containing collections) and use that to pass a 'batch' of information.
    Hopefully this will get addressed in the next release of the database.

  • Sending Hebrew Strings From Java to ABAP

    Hello everybody,
    I'm trying to send a string from WebDynpo Java code to a SAP transaction on the R3 system.
    When I'm sending a string in English it arrives correctly
    When I'm sending a string in Hebrew it arrives as a sequence of question marks.
    Does anyone knows what kind of conversions do I need to do so I'll be able to send Hebrew strings?
    Thanks in advance, Adi.

    Hi,
      When u say that you are sending a hebrew string did you localized ur string usig ResourceBundle class from your Webdynpro,check it first.
      Refer SAP OSS notes for how to send String other than English to R/3 system and detailed configuration required.
      Refer this for help on Localization,
    • Internationalization is used for adapting already existing Webdynpros application
    Without changing the source code so that they can be used in several multi lingual languages.
    • Here we keep text strings separately from the application source code in a particular format(keys & values) so they can be processed in the standard translation mechanism.
    • Here frequently used texts such as labels or titles are stored as java dictionary simple types objects.
    • To do internationalization, copy the automatically generated *.xlf files and save them under the new name in the same directory.
    • For eg :- file convention like <old filename>_<language key>.xlf. Ex:- For German use the language key de.
    • For a particular user the locale is specified by the User management engine.
    • If not the locale is handled by the browser setting(HTTP Headers)
    • If not the default locale specified by the application will be returned.
    • If not default locale of the Virtual Machine(VM) is returned
    • This locale is passed to java.lang.ResourceBundle in the J2EE engine.
    • This will load the physically existing resource bundle either from any one of the following :-
    Resource bundle of WD(if exists) or resource bundle of VM (if exists) or
    Resource Bundle of without language suffix(always exists) given by the developer.
      I will post if anything strikes me.
    Hope it helps.
    Regards,
    Guru

  • Passing a structure from Java to PL/SQL Procedure

    Environment: Oracle DB, Tomcat/Apache
    How do we pass a structure (Table Record Type) from Java to a PL/SQL Stored Procedure?
    We are doing JSP-->JavaClass/Bean to communicate to DB. We have an existing PL/SQL packages/Procedure to insert records into table (These procedures have record types as in/out parameters). So is there a way to call these from Java?
    Thanks in advance.
    Ramesh

    Oracle9 i JDBC Developers Guide and Reference(page 21-16):
    It is not feasible for Oracle JDBC drivers to support calling arguments or return
    values of the PL/SQL RECORD, BOOLEAN, or table with non-scalar element types.
    However, Oracle JDBC drivers support PL/SQL index-by table of scalar element
    types. For a complete description of this, see "Accessing PL/SQL Index-by Tables"
    on page 16-21.
    As a workaround to PL/SQL RECORD, BOOLEAN, or non-scalar table types, create
    wrapper procedures that handle the data as types supported by JDBC. For example,
    to wrap a stored procedure that uses PL/SQL booleans, create a stored procedure
    that takes a character or number from JDBC and passes it to the original procedure
    as BOOLEAN or, for an output parameter, accepts a BOOLEAN argument from the
    original procedure and passes it as a CHAR or NUMBER to JDBC. Similarly, to wrap a
    stored procedure that uses PL/SQL records, create a stored procedure that handles
    a record in its individual components (such as CHAR and NUMBER) or in a structured
    object type. To wrap a stored procedure that uses PL/SQL tables, break the data
    into components or perhaps use Oracle collection types.

  • Return national language strings from java stored procedures

    Hi, all.
    How does i can return String which contains national characters from java stored procedure? I.e. convert UTF java string to national language of database. It's does not processing automatically (why?).
    declaration of procedure:
    CREATE OR REPLACE FUNCTION TestNLSString RETURN VARCHAR2
    AS
    LANGUAGE JAVA
    NAME 'test.SomeClass.getNLSString() return java.lang.String';
    SELECT TestNLSString AS X FROM DUAL;
    X
    iiiii
    OS: Windows 2000 Server
    Oracle Server version: Oracle 8.1.7.1.4

    Ok. I had a specific problem.
    I want to use java stored procedure (function) to make a connection to remote db using supplied connection parameters make some quieries there end return results in a form of structured data - object.
    I have defined an object type in a database where the function will reside. I granted execute privilege to public user on this type, made public synonyms to both, the object type and the function, so anybody connected to the same database would have an access to this functionality.
    I supposed that if I supply connection parameters for some other user but the same database when running the function, everything should go smooth. Yeah.
    My java code executed ok: it made a connection to the db with some x user, it resolved object type descriptor given (oracle.sql.StructDescriptor), but pl/sql wrapper function reported the error I've mentioned. If I executed the function giving it the connection parameters for same account as where object type was declared, everything went fine.
    My final solution is:
    Make TWO! connection in java code: 1st for ("jdbc:default:connection:"), 2nd for remote database account.
    Use first connection to construct oracle.sql.StructDescriptor
    Use second connection to retreive data from remote db

  • Why returning string from java stored function failed ?  HELP ME, PLEASE

    Hi everybody,
    I created java stored function: it's doing http post, parsing xml from http reply, and returning string result.
    Sometimes, it doesn't return any value. What can be a reason ?
    The high level procedure, has following form:
    class SBE {
    public static String call(String arg0) {
    SBE sbe=new SBE("d:\\oracle\\ora81\\network\\log\\SBE.log");
    String result=SBEParser.go(sbe.sendRequest(arg0, ""), sbe.logger);
    sbe.logger.log(result);
    sbe.logger.log("Finish SBE intetraction");
    return result;
    PLSQL wrapper has a simple form:
    create or replace package PG_SBE as
    function CALL(arg0 in varchar2) return varchar2;
    end;
    create or replace package body PG_SBE as
    function CALL(arg0 varchar2) return varchar2 as language java name 'SBE.call(java.lang.String) return java.lang.String';
    end;
    In log file ("d:\\oracle\\ora81\\network\\log\\SBE.log"), I can find message :
    "Finish SBE intetraction"
    but query:
    select pg_sbe.call("any argument") from dual;
    doesn't finish.
    What can be a reason ? What can I do to trace stage of convertion java string to varchar ?
    Please help me...
    Best regards
    Marek

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Stefan Fdgersten ([email protected]):
    Maybe your call is wrong... Shouldn't there be a "?" instead of "1"?
    Your code:
    String myquery = "begin :1 := jspTest; end;";
    I provide my (working) call from java as an example. Maybe it is of any help... :)
    import java.sql.*;
    import oracle.jdbc.driver.*;
    public Vector getAllHosts() throws SQLException {
    //return getHosts(false, -1);
    Connection conn = null;
    CallableStatement cs = null;
    Vector hostV = new Vector();
    try {
    conn = getConnection();
    String query = "{ ? = call curTestPkg.curTestFunc}";
    cs = conn.prepareCall(query);
    cs.registerOutParameter(1, OracleTypes.CURSOR);
    cs.execute();
    ResultSet rs = ((OracleCallableStatement)cs).getCursor(1);
    while (rs.next()) {
    Host host = new Host(
    rs.getInt("hostid")
    , rs.getString("name")
    , rs.getString("descr")
    , rs.getString("os"));
    hostV.add(host);
    cs.close();
    return hostV;
    } finally {
    close(conn, cs);
    <HR></BLOCKQUOTE>
    hi Stefan thanx.....even after changing the call statement i get the same error. i changed query string as...
    String myquery = "{ ? = call jspTest}";
    CallableStatement cst = con.prepareCall(myquery);
    Can u please check out my call sepc that i have written in pl/sql and plz let me know it there is any error in that.
    PS : THIS IS THE FIRST TIME I AM WORKING WITH PL/SQL AND IT IS URGENT

  • How to pass a string from a servlet to client side

    hi,
    i would like to generate a string from a servlet and pass it to the client side. the client will receive the string by using request.getParameter(). How should i implement this system? Could anybody give me some hint?
    Best Regards,
    Henry

    Greetings,
    hi,
    i would like to generate a string from a servlet and
    pass it to the client side. the client will receive
    the string by using request.getParameter(). HowAre you referring to the instance of (Http)ServletRequest the 'request' object being passed to the "client"? What is the "client" in this case? If you mean a "traditional" client communicating over (or by tunneling through...) HTTP then no can do. The (Http)ServletRequest object is generated by the web container (a.k.a. "servlet engine"), not by the client, and it is not serializable so there is no way to pass it back to the client...
    should i implement this system? Could anybody give me
    some hint?It depends again on "what is the 'client' in this case?"
    Best Regards,
    HenryRegards,
    Tony "Vee Schade" Cook

  • Passing a string from c# to RunState.Root.Locals.UUT.SerialNumber at NI

    HI all,
    How can I pass a variable content as a string in c# to the sequence variable named as RunState.Root.Locals.UUT.SerialNumber.
    The main gold is to pass the string value from textbox in c# GUI to the sequence parameters.
    Tnx

    Hi
    there a serveral ways to do this task. But you should do it in that way Norbert_B has descriped by using UserInterface Messages.
    In general, TestStand is not only one process. Your UI is another process. You have to share information over processes.
    The recommed way for doing this here is fireing UI messages. From TestStand execution you send a message to your UI. Once you have received this message in your UI, you can get a handle to the current sequnceContext were you are able to set your UUT number.
    I am pretty sure that Norbert can explain this more in detail. :-) because i am out of time now.
    Regards
    Juergen
    =s=i=g=n=a=t=u=r=e= Click on the Star and see what happens :-) =s=i=g=n=a=t=u=r=e=

  • Returning strings from Java- C JNI calls

    <newbie to JNI>
    I have an application written in Java that accesses a .DLL written in C. The .DLL does low-level communication to a hardware device. I've got it all working except for one little problem:
    For all of the functions I need to return an integer return code and for some of them I also need to return a string, such as a serial number, version string, or whatever.
    Try as I might, I can't find any information on how to return two values from a function call (pretty sure I can't in Java).
    SO, I tried to find out how to stuff the version string into a string object variable in the class object the DLL API is defined in. I can't figure out how to do that either...
    e.g. the following Java code:
    class LLDev {
    /* --- Load the .DLL -------------------- */
    static { System.loadLibrary("LLDev"); }
    /* --- Error Codes ---------------------- */
    public static final int LLDOk = 0;
    public static final int LLDInitErr     = -1;
    /* --- Public Variables ----------------- */
    public static String DLLVersion;
    /* --- Public Methods ------------------- */
    public native int InitLLDev();
    When I invoke LLDev.InitLLDev() from Java I want the C .DLL function Java_LLDev_InitLLDev to put the DLL Version string in the LLDev object's DLLVersion field and return an error code as the function result.
    Is this possible???? Is this the right way to do this?? I tried to define the API with methods that return strings instead of integer return codes but the customer using the class wants all of the methods to return a return code in case of some error (e.g. reading the serial number from the device could fail...)

    1. In general, the java way to deal with errors is by throwing exceptions, not using return codes. But OK, you are stuck with the user requirement.
    2. I suggest you have the native method take as an argument a java object which will accept a string as input. In other words, it has a string "setter".
    3. So in your native method, if the function succeeds, it writes your string result to that object, and you can futrther process it when the native method returns a "success" code.
    4. There are JNI methods for
    o looking up the class of a java object.
    o looking up the method of a java class.
    o invoking the method.

Maybe you are looking for

  • Could not open the file. An internal error occurred.

    Hi, Anyone can solve my problem? Urgent! I can't open a png file. Others files was ok, just only one file can't open after save. It show : Could not open the file. An internal error occurred. Thanks!

  • Discussion Server Authentication Failed From Inside FMW App

    Hi Community, My Env: Webcenter 11.1.1.3.0 Weblogic 10.3.3 The discussion server shipped with webcenter suite is Jive Forums Silver 5.5.20 .2-oracle. I wired the discussion server to embedded LDAP server of my weblogic server, and deployed an app tha

  • Errors:"Could not find Web Ser"- "Failed to Lunch E1 menu on HTML Engine"

    Hi all I am trying to install JD Edwards EnterpriseOne and I am using two different machines. First machine: Installed Enterprise and Database Server Second Machine: Installed Deployment Server. Installed Oracle Application Server. Installed Server M

  • Filtering mac on switch

    Hi everyone, i have a two switches for two seperate depts,i would like to configure mac address filtering on the switch so that users cannot communicate with each other.can someone help with configuration guide.

  • Can't log on to Internet

    I can't get my iPhone 4S to log on to my friends Internet connection but my brand new iPad with retina display logged on immediately with very few prompts. What am I doing wrong? Or is it that my iPhone's processor isn't as up to date as the new iPad