1 Reply Latest reply: Jul 14, 2011 4:28 PM by jschellSomeoneStoleMyAlias RSS

    c/c++ structs as parameters and return results

    875648
      Hello all,

      I have a few questions regarding the usage of JNI. Assume that there is a function in C which returns a pointer to a struct variable (which has been appropriately allocated). Furthermore the function head takes a pointer to a struct variable as a parameter. This struct however declares a field within it, which is a pointer to a function. Before returning a struct variable the function pointer field within it is set in the function body (and some other C specific stuff happens there).
      Since I can't implement this function as a java method directly I have to call it using JNI. However I have to declare the function head in my java class (using the "native" keyword). Unfortunately I'm not sure how I can write a class in java which has a "method/function pointer"-field within it to match the return value of the function in C or the problematic parameter in the function head. Can anybody help me with what to do in this case? Maybe the problem can be circumvented instead of solved directly. I'm open to any suggestions.

      Thanks for your time.

      Chris.
        • 1. Re: c/c++ structs as parameters and return results
          jschellSomeoneStoleMyAlias
          Since I can't implement this function as a java method directly I have to call it using JNI.
          JNI is intended as an abstraction layer between Java and required functionality in another language (normally C/C++).

          Thus you use it like this.
          1. Write and debug your C/C++ code.
          2. Write your java code.
          3. Add JNI method to connect 1 and 2.

          From the above you would NEVER attempt to call a method directly because it breaks the abstraction model.
          Can anybody help me with what to do in this case?
          Presumably you want to pass a pointer.
          1. In JNI method 1: cast pointer to a java long an return it.
          2. In java code store the long.
          3. Call JNI method 2 passing the long value.
          4. In JNI method 2: cast the long to a pointer.

          Additionally you probably need to dynamically allocate the pointer, thus you MUST determine how you are going to clean it up at some point.