python ctype string pointer 32b vs 64b: segmentation fault (core dumped)

I have a shared library that, amongst other things, contains this function:

char * LibVers()
{
    return " LibVers 2.03";
}

I am wrapping said shared library using ctypes and have a property defined liked so:

@property
def lib_vers(self):
    """Get shared library version information.

    :return: The shared library version string.
    :rtype: String
    """
    return c_char_p(self.lib.LibVers()).value

On a 32b machine (Fedora 16) this code works fine. However, on a 64b machine (CentOS 7) this code segmentation fault (core dumped).

Why would that be?

Upvotes: 1

Views: 455

Answers (1)

The ctypes modules assumes that the return type is a c_int. If not, you have to provide the return type yourself and do some conversion. Mostly, on 32 bits, this works out as fine but on 64, you lose some part of the pointer thus making it invalid. I changed the code to the following and it now works as expected.

@property
def lib_vers(self):
    """Get shared library version information.

    :return: The shared library version string.
    :rtype: String
    """
    if self.lib.LibVers.argtypes is None:
        self.lib.LibVers.restype = c_char_p
        self.lib.LibVers.argtypes = []
    return self.lib.LibVers()

Upvotes: 1

Related Questions