#StackBounty: #java #c++ #java-native-interface #swig swig: correct way to typemap a C++ buffer pointer in a result object back to java

Bounty: 50

Foo.h that I want to swig:

#include <cstdint>

class Result
    Result(const uint8_t *resultBuffer, int width, int height);

    const uint8_t *result;
    int width = -1;
    int height = -1;

class Foo
    Result doThing();

    Context ctx;

Under the hood, Foo.doThing() does this:

// Context.buffer, a uint8_t*, points at allocated memory.
// that memory gets automatically freed when the Foo instance goes away.
// some stuff is written to ctx.buffer.
// int variables "bufferWidth" and "bufferHeight" are updated.
// multiplying them together gives size of ctx.buffer.
// finally:
Result result(ctx.buffer, ctx.bufferWidth, ctx.bufferHeight);
return result;

I want the result buffer to be a ByteBuffer on the Java side. After some googling I came up with this swig interface file:

%module FooSwigModule

%include "stdint.i"

// FIXME:  likely wrong
%include "various.i"
%apply unsigned char *NIOBUFFER { uint8_t *resultBuffer };

/* Includes the header in the wrapper code */
#include "Foo.h"

/* Parse the header file to generate wrappers */
%include "Foo.h"

Java side:

    Foo foo = new Foo();
    Result result = foo.doThing();
    int width = result.get_width(); // OK
    int height = result.get_width(); // OK
    ByteBuffer byteBuffer = result.get_result(); // SIGSEGV here
    // do things with result.get_result(), width, and height
    // ...

What should replace the two lines below FIXME in the swig interface file?

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.