Leonid
Leonid

Reputation: 81

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

Upvotes: 0

Views: 330

Answers (3)

Cory
Cory

Reputation: 1559

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)

Upvotes: 0

David
David

Reputation: 388

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

Upvotes: 0

EyalAr
EyalAr

Reputation: 3170

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.

Upvotes: 5

Related Questions