Question

I am working on a Java app that has a callback from a native c library. The callback passes back the following c struct;

struct session
{
    unsigned media_count;/**< Number of media.      */
    media *media[10];   /**< Media array.   */

};

struct media
{
    struct
    {
        char    media_name[];   
    } desc;

/*
  Stuff im not interested in..  
*/
};

In the swig interface file I have the following;

core.i
------

typedef struct session
{
    unsigned    media_count;
} session;

Then in the Java callback implementation I end up with;

void call_back(session session) {
    session.get_media_count();
}

As expected, however I now want to expose the media array to Java. I have the following;

core.i
------

struct media
{
} media;

typedef struct session
{
    unsigned    media_count;
    media media[10];
} session;

But this is giving me a single media item in Java eg;

void call_back(session session) {
    session.get_media_count();
    media media = session.get_Media();
}

When I want;

void call_back(session session) {
    session.get_media_count();
    media[] media = session.get_Media();
}
Was it helpful?

Solution

A while ago I solved a similar task by creation of a custom read-only "vector-like" class with at() method exposed as get(int i) on java level. The main idea is that you don't have to have the same class on native and swig level. Actually you construct SWIG-level almost independently from C/C++ level. The key method of the construction is %extend SWIG-directive, something like this:

%{
#include "session.h"
%}
%extend session {
    const media& getMedia(int i) {
        return media[i];
    }
}

But be aware, that while performing tricks like that I literally felt that I was doing something really evil. Like studying The Dark Forces from "Harry Potter" ;-) And afterall, I discovered that doing a lot of Java<->native code switches performs not that good as expected.

Also I doubt you could return an "array object" from native code and use it safely from Java, because such an access heavily depends on low-level data alignment, and you don't have methods to directly translate C-level data to Java-level data without extra copyings

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top