ctypes - Beginner

后端 未结 3 1944
情歌与酒
情歌与酒 2020-11-28 17:42

I have the task of \"wrapping\" a c library into a python class. The docs are incredibly vague on this matter. It seems they expect only advanced python users would implem

3条回答
  •  情歌与酒
    2020-11-28 18:03

    Here's a quick and dirty ctypes tutorial.

    First, write your C library. Here's a simple Hello world example:

    testlib.c

    #include 
    
    void myprint(void);
    
    void myprint()
    {
        printf("hello world\n");
    }
    

    Now compile it as a shared library (mac fix found here):

    $ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c
    
    # or... for Mac OS X 
    $ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c
    

    Then, write a wrapper using ctypes:

    testlibwrapper.py

    import ctypes
    
    testlib = ctypes.CDLL('/full/path/to/testlib.so')
    testlib.myprint()
    

    Now execute it:

    $ python testlibwrapper.py
    

    And you should see the output

    Hello world
    $
    

    If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

    This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

    PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

提交回复
热议问题