ben soft
ben soft

Reputation: 21

How to pass structure by reference with JNA

I want to call this function :

extern "C" xxx_SERVICE_API int  initSocket(socketStruct* skStruct); 

defined in a c++ dll.socketStruct is a structure defined below:

typedef struct 
{
    int a;
    int b;
} mystruct;

equivalent code in java is :

public interface MyDllClass extends Library {

    public static class MyStructure extends Structure {

        public static class ByReference extends MyStructureRef
        implements Structure.ByReference{ 


        }
        @Override
        protected List<String> getFieldOrder() {    

            return Arrays.asList(new String[]{"a","b"});
        }
        public int a;
        public int b;
    }
    //Native function
    int initSocket (MyStructure.ByReference sks); 
    MyDllClass INSTANCE = (MyDllClass)Native.loadLibrary("Mydll",  
    MyDllClass.class); 
}

How can i call this native fucntion with the structure by reference as parameter? Thank you

Thank you for your answer. According with you i add a contructor to my structure:

public interface MyDllClass extends Library {

    public static class MyStructure extends Structure {

       public MyStructure() {

            idModule = 0;
            nbModules = 0;
            nbQueueInModule = 3;
            portList = new int[128];
            serverList = new char[128][20]; 
        }
        @Override
        protected List<String> getFieldOrder() {    

            return Arrays.asList(new String[]{"a","b","portList","serverList"});
        }
        public int a;
        public int b;
        public int[] portList;
        public char[][] serverList;
    }
    //Native function
    int initSocket (MyStructure.ByReference sks); 
    MyDllClass INSTANCE = (MyDllClass)Native.loadLibrary("Mydll",  
    MyDllClass.class); 
}

In the main I wrote this code :

MyStructure mySocket = new MyStructure();
MyDllClass.INSTANCE.initSocket(mySocket);

This code fail because of Null pointer exception when calling the native function. Do you have an idea ?

Upvotes: 1

Views: 4185

Answers (1)

technomage
technomage

Reputation: 10069

All JNA Structure parameters default to by reference (struct*) semantics.

When appearing as structure members, they default to by value semantics.

The ByReference and ByValue tagging interfaces are provided for use where you want the complementary behavior. If the default behavior is what you want, you don't need the extra typing.

You should always provide a Pointer-based constructor to Structures you define, it avoids superfluous memory allocation by JNA.

Upvotes: 1

Related Questions