title: C++'s out parameter object creation and JNA
body: <p><em>Disclaimer: I ignore pretty much everything about C++, so I hope I'm not saying stupid things here, if I am, please feel free to correct me.</em></p>
  
  <p>As a Java developer, when I want to create a new object, I use a constructor method that will allocate this object in memory and return a handle on it for me, and I will store this handle in a variable, I do it like this.</p>
  
  <pre><code>Foo o = new Foo();
  </code></pre>
  
  <p>But in C++, I've been given to understand, that despite the fact it is possible to do so </p>
  
  <pre><code>Foo createFoo(){
      Foo f;
      f.doSomething();
      return f;
  }
  
  // ...
  
  Foo f = createFoo();
  </code></pre>
  
  <p>I can also define a handle by myself, and then call a initializer on it that will allocate memory and bind the handle on it, like this:</p>
  
  <pre><code>void initializeFoo(Foo **f){
      f.doSomething();
      return;
  }
  
  // ...
  
  Foo f;
  initializeFoo(&amp;f);
  </code></pre>
  
  <p>So my question is, what happens when we want to use those C++ methods in Java, with JNA?</p>
  
  <p>Let's suppose I have the following C++ header:</p>
  
  <pre><code>typedef struct Foo f;
  
  Foo createFoo();
  void initializeFoo(Foo **f);
  </code></pre>
  
  <p>As I don't have any idea on what a Foo is, or what the Foo structure contains, I'm just going to create a JNA PointerType to declare my structure:</p>
  
  <pre><code>public class Foo extends PointerType{
  
      public Foo(Pointer address) {
          super(address);
      }
      public Foo() {
          super();
      }
  }
  </code></pre>
  
  <p>Using the createFoo method should be pretty easy as well:</p>
  
  <pre><code>public class TestFoo{
      static{
          System.loadLibrary("foolib");
      }
  
      public static void main(String[] args){
          FooLib lib = (FooLib)Native.loadLibrary("foolib", FooLib.class);
  
          Foo f = lib.createFoo();
      }
  </code></pre>
  
  <p>Right?</p>
  
  <p>But my question is, how can I use the initializeFoo function??? I suppose I would have to create a Pointer and give it to the function, but how do I create a non NULL pointer in JNA? I tried the following code, but it results in an EXCEPTION_ACCESS_VIOLATION.</p>
  
  <pre><code>public class TestFoo{
      static{
          System.loadLibrary("foolib");
      }
  
      public static void main(String[] args){
          FooLib lib = (FooLib)Native.loadLibrary("foolib", FooLib.class);
  
          Foo f = new Foo();
          lib.initializeFoo(f); // EXCEPTION_ACCESS_VIOLATION
          lib.initializeFoo(f.getPointer()); // EXCEPTION_ACCESS_VIOLATION
      }
  </code></pre>
  
  <p>Any idea?</p>
  
  <p>Thanks!</p>