I have a C function that I want to call using Java via SWIG but I’m unsure how to handle the sockaddr_in C structure. Anyone have any examples on how I can handle the sockaddr_in?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s actually an article on wrapping
sockaddr_inon swig.org, although it looks slightly old now.Basically what they did was write a function that creates a new
sockaddr_infor you, taking arguments for the values that need to be filled in as things that are easy to pass around in Java. This is a slightly updated, trimmed version of the linked article:There’s a nicer way of wrapping this with SWIG though, we can write a typemap to use
java.net.InetSocketAddressinstead, which will feel far more “natural” on the Java side of the interface:Basically this calls the
getAddress()andgetPort()methods ofjava.net.InetSocketAddressand uses the result to create astruct sockaddr_infor the call.Notes:
InetSocketAddressto see which sub-class it is in the typemap itself.outtypemap. This is basically the reverse procedure, the JNI code will create new Java objects for us.For completeness there’s also a third possible way of wrapping this, which involves no JNI, but writing a little bit of Java. What we do is have SWIG wrap the
struct sockaddras in the first example, but then have the wrapped functions that usesockaddrreturn ajava.net.InetSocketAddressobject still and supply some code for converting between the two. I’ll give an example with an “out” typemap, i.e. for returning from functions.Given:
we can wrap it with:
We’ve specified how to wrap a
sockaddr_indirectly, but also instructed the return from the function itself to be the more appropriate Java type (%typemap(jstype)) and provided a small amount of Java to perform the conversion (%typemap(javaout)). We could do similar for an in typemap too. This doesn’t handleAF_INET6addresses properly – I can’t find an equivalent ofInetAddress.getByAddress()for IPv6 addresses, so there should probably be an assert/exception for that case.