1. create a dynamic link library:
gcc -shared -fPIC -o share_lib.so share_lib.c2. the use of a .so: gcc main.c ./share_lib.so -o main
main.c:
#includeint main(int argc, char *argv[]){ int array[5] = { 5, 4, 3, 2, 1}; int item; int pos; insert_sort(array, 5); printf("please input a number\n"); scanf("%d", &item); pos = binary_search(array, item, 5); if(pos == -1){ printf("cant't find\n"); }else{ printf("the position is %d\n", pos+1); } return 0;}
share_lib.c:
// insert sort functionvoid insert_sort(int *array, int length){ int i, j; for(i = 0; i < length; ++i){ int temp; j = i; temp = array[i]; while(j > 0){ if(temp < array[j - 1]){ array[j] = array[j - 1]; --j; }else{ break; } } array[j] = temp; }}// binary searchint binary_search(int *array, int item, int length){ int high, low, mid; high = length - 1; low = 0; mid = (high + low) / 2; while(low < high){ if(array[mid] > item){ high = mid; mid = (high + low) / 2; }else if(array[mid] < item){ low = mid; if( (high + low) % 2 == 0) mid = (high + low) / 2; else mid = (high + low)/2 + 1; }else return mid; } return -1;}void bubble_sort(int *array, int length){ int i, j; int exchange = 1; i = 0; int temp; while(i < length && exchange){ j = length - 1; exchange = 0; while( j > i){ if(array[j] < array[j - 1]){ temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; exchange = 1; } --j; } i++; }}
python call *.so:
#! /usr/bin/python from ctypes import * import os libtest = cdll.LoadLibrary(os.getcwd() + '/share_lib.so') TenIntArrayType = c_int * 10; arr = TenIntArrayType(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) #for i in xrange(10): # arr[i] = 10 - i libtest.insert_sort(pointer(arr), 10) print libtest.binary_search(pointer(arr), 3, 10)
pack multiple .c files to one .so:
gcc -Wall -fPIC -c *.o gcc -shared -o so_name *.o