SWIG binary string caveat

If you have been working with Web services you might have heard the term MTOM. I was getting MTOM support to work on WSF/Perl and the image that was not getting saved properly. Only the first few bytes was written to the file. The magic numbers that were getting saved was enough for the file command to say it’s a JPEG image. From the C layer it was reading image data to a character pointer and returning it to the scripting language.

The C function reading the image had a char * return type. The code that was generated by SWIG was returning the pointer after running it through the following function,

SWIG_FromCharPtr(const char *cptr)
{
  return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0));
}

The rough English translation of the above is, “you’re screwed”. Why? The strlen doesn’t particularly like to go through binary strings. It’ll choke and die when it see a null byte. So, only the content before the null byte was returned.

The solution was to create a string using the API provided by the particular scripting language. For Perl it’s newSVpv and for Ruby it’s rb_str_new. Wrapped the functions inside an ifdef (thanks to the nice SWIG<lang> defines) and all is set for MTOM!

4 Comments

  • May 1st 200802:05
    by Nirmal

    engwar.com home came closest on the W3 Validator: only 1 error ;) . very nice site btw. oh, you’re using reCAPTCHA, too? cool…

    i think i read some linux related thing you wrote for ITTIMES agez ago: am i ryt?

  • May 2nd 200801:05
    by Chintana

    The syntax highlighter I use rely on the name attribute for the pre tag Nirmal.

    Thanks! Yes, it was me :-)

  • Feb 7th 200916:02
    by Martin Streicher

    Can I see your example in Ruby? I am trying to get binary data back from a C function and am having issues.

  • Feb 14th 200914:02
    by Chintana

    @Martin: Sorry for the late reply, the code is here – http://svn.wso2.org/repos/wso2/trunk/commons/swig/wsf_inlines.i

    Lines 26 – 38.

  • Leave a Reply