简体   繁体   中英

call c function from python

I have code in c :

typedef struct {
int bottom;
int top;
int left;
int right;
} blur_rect;

int bitmapblur(
char* input,
char* output,
blur_rect* rects,
int count,
int blur_repetitions);

I need use the bitmapblur function from python . How I do it? The question about array of structs.

THX

you will need to compile your c code as a shared library and then use the 'ctypes' python module to interact with the library.
I recommend you start here .

This can be usefull too: "Extending Python with C or C++", starting with a simple example. U can find more about it here .

You will first need to use ctypes. First, build a struct:

import ctypes

class BlurRect(ctypes.Structure):
    """
    rectangular area to blur
    """
    _fields_ = [("bottom", ctypes.c_int),
                ("top", ctypes.c_int),
                ("left", ctypes.c_int),
                ("right", ctypes.c_int),
                ]

Now load your function. You will need to figure out the best name for the shared library, and then load it. You should have this code already implemented as a dll or .so and available in the ld path.

The other tricky bit is your function has an "output" parameter, and the function is expected to write its result there. You will need to create a buffer for that.

The ctypes code will look something like this:

blurlib = ctypes.cdll.LoadLibrary("libblur.so")
outbuf = ctypes.create_string_buffer(1024) # not sure how big you need this

inputStructs = [BlurRect(*x) for x in application_defined_data]

successFlag = blurlib.bitmapblur("input", 
    outbuf,
    inputStructs,
    count,
    reps)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM