Chris
Chris

Reputation: 10101

Best way to call C-functions from python?

I've written a high level motor controller in Python, and have got to a point where I want to go a little lower level to get some speed, so I'm interested in coding those bits in C.

I don't have much experience with C, but the math I'm working on is pretty straightforward, so I'm sure I can implement with a minimal amount of banging my head against the wall. What I'm not sure about is how best to invoke this compiled C program in order to pipe it's outputs back into my high-level python controller.

I've used a little bit of ctypes, but only to pull some functions from a manufacfturer-supplied DLL...not sure if that is an appropriate path to go down in this case.

Any thoughts?

Upvotes: 2

Views: 1510

Answers (4)

tebanep
tebanep

Reputation: 645

You can use Cython for setting the necessary c types and compile your python syntax code.

Upvotes: 0

kaitian521
kaitian521

Reputation: 588

you can use SWIG, it is very simple to use

Upvotes: 0

Guy Adini
Guy Adini

Reputation: 5504

Another option: try numba. It gives you C-like speed for free: just import numba and @autojit your functions, for a wonderful speed increase.

Won't work if you have complicated data types, but if you're looping and jumping around array indices, it might be just what you're looking for.

Upvotes: 0

user1786283
user1786283

Reputation:

You can take a look at this tutorial here.

Also, a more reliable example on the official python website, here.

For example,

sum.h function

int sum(int a, int b)

A file named, module.c,

#include <Python.h>
#include "sum.h"

static PyObject* mod_sum(PyObject *self, PyObject *args)
{
    int a;
    int b;
    int s;
    if (!PyArg_ParseTuple(args,"ii",&a,&b))
       return NULL;
    s = sum(a,b);
    return Py_BuildValue("i",s);
}

static PyMethodDef ModMethods[] = {
    {"sum", mod_sum, METH_VARARGS, "Description.."},
    {NULL,NULL,0,NULL}
};

PyMODINIT_FUNC initmod(void)
{
    PyObject *m;
    m = Py_InitModule("module",ModMethods);
    if (m == NULL)
       return;
}

Python

import module
s = module.sum(3,5)

Upvotes: 2

Related Questions