Using ctypes to grab a pointer from a nullary function (segfault) x64
Question: I've reduced my problem to the following toy file and command:

    
    
    // a.c --> a.out, compiled with `gcc -fPIC -shared a.c`
    void* r2() {
      return NULL; // <-- could be anything
    }
    

`python -i -c "from ctypes import *; clib =
cdll.LoadLibrary('/home/soltanmm/tmp/a.out');
CFUNCTYPE(c_void_p).in_dll(clib,'r2')()"`

^ results in a segfault in a call directly within `ffi_call_unix64`.

I'm on an AMD64 Linux machine running Python 2.7. What am I doing wrong?

## EDIT

To lend weight to how the pointers don't matter, a second example that
segfaults:

    
    
    // a.c --> a.out
    int r1() {
      return 1;
    }
    

`python -i -c "from ctypes import *; clib =
cdll.LoadLibrary('/home/soltanmm/tmp/a.out');
CFUNCTYPE(c_int).in_dll(clib,'r1')()"`


Answer: CFUNCTYPE is used for callbacks (or pointers to functions defined as a
variable in the shared object). After you do `cdll.LoadLibrary` you should
simply be able to call `C` functions on the returned library object directly.
So something like this should work:

    
    
    from ctypes import *;
    clib = cdll.LoadLibrary('/home/soltanmm/tmp/a.out');
    print(clib.r2())
    

Method `in_dll` is generally used to access **variables** that are exported
from shared objects. Not functions themselves. An example of using `in_dll`
would be something like this:

File **a.c** :

    
    
    #include <stdlib.h>
    
    int r2() {
        return 101;
    }
    
    int (*f)(void) = r2;
    char *p = "Hello World";
    
    char *gethw() {
        return p;
    }
    

Python script:

    
    
    from ctypes import *;
    clib = cdll.LoadLibrary('/home/soltanmm/tmp/a.out');
    
    # print should call r2() since f is a variable initialized to
    # point to function r2 that returns an int. Should 
    # print 101
    print (CFUNCTYPE(c_int).in_dll(clib,'f')())
    
    # or call r2 directly
    print(clib.r2())
    
    # prints out the character (char *) string variable `p'
    # should result in 'Hello World' being printed.
    print((c_char_p).in_dll(clib,'p').value)
    
    # call the gethw() function that returns a point to a char *
    # This too should print 'Hello World'
    # we must set the restype c_char_p explicitly since the default
    # is to assume functions return `int`
    gethw = clib.gethw
    gethw.restype = c_char_p
    print(gethw())
    

More on the usage of ctypes can found in the [Python
Documentation](https://docs.python.org/3/library/ctypes.html)

