1

I am trying this the wrapper example provided on this webpage I've found: https://pgi-jcns.fz-juelich.de/portal/pages/using-c-from-python.html

I've created a C file called sum.c:

int our_function(int num_numbers, int *numbers) {
    int i;
    int sum;
    for (i = 0; i < num_numbers; i++) {
        sum += numbers[i];
    }
    return sum;
}

then compiled it using:

cc -fPIC -shared -o libsum.so sum.c

then wrote a sum.py file try to call it:

import ctypes

_sum = ctypes.CDLL('libsum.so')
_sum.our_function.argtypes = (ctypes.c_int, ctypes.POINTER(ctypes.c_int))

def our_function(numbers):
    global _sum
    num_numbers = len(numbers)
    array_type = ctypes.c_int * num_numbers
    result = _sum.our_function(ctypes.c_int(num_numbers), array_type(*numbers))
    return int(result)

and then I wrote a test.py file try to call this C functions in python:

import sum
print sum.our_function([1,2,-3,4,-5,6])

however this error is poping up and I dont know why because I can clearly see the libsum.so in the folder there

OSError: libsum.so: cannot open shared object file: No such file or directory
Gabriel Devillers
  • 3,155
  • 2
  • 30
  • 53
Yuan
  • 19
  • 1

1 Answers1

0

probably 2 years late.. but..

change

_sum = ctypes.CDLL('libsum.so')

to

import os
_sum = ctypes.CDLL(os.path.abspath('libsum.so'))

it solved the problem for me