LeafTeaNeko
LeafTeaNeko

Reputation: 123

Using a C library with Python on Raspi

I'm trying to use a time of flight sensor on a Raspi (Pololu VL53L1X) but there are no libraries for the sensor in python. The original manufacturer has provided with a C API for the sensor but I dont know how to use the API functions in my python code. Can someone help me understand what I can do use the sensor on Raspi without having to write the library from scratch? I've done some research and almost everyone suggests wrapping C libraries(API in this case?) in python but Im not sure how to do that. Any ideas or suggestions would be valuable.

P.S. There are libraries for the sensors for Arduino but I cant use Arduino and I need it to run on Raspi and using python if possible. I'm a beginner to Raspi and Python so a little explanation on your idea would be helpful.

Upvotes: 0

Views: 139

Answers (1)

PunyCode
PunyCode

Reputation: 373

Making a simple python wrapper for a c library.

I got the following files in my work directory

mylib.c :

#include <stdio.h>

int sumof(int a, int b)
{
    return a+b;
}

wrapper.py :

from ctypes import CDLL
so_file = "/path/to/my/work/dir/mylib.so"
my_c_lib = CDLL(so_file)

def sumof_fun(a,b):
    return my_c_lib.sumof(a,b)

As you can see we are using a shared library (.so file) in the python wrapper for creating that shared library we use following command:

$gcc -fPIC -shared -o mylib.so mylib.c

Now in python I could use following:

>>> import wrapper
>>> 
>>> wrapper.sumof_fun(4,5)
9

Ref: https://www.journaldev.com/31907/calling-c-functions-from-python

PS : But in your case I still believe its better to go for pimoroni vl53l1x-python package

Upvotes: 1

Related Questions