2020年3月5日 星期四

python - cffi (python embedded C)

cffi: C Foreign Function Interface for Python

ENV: python 3.6 + cffi 1.14 at x86_64

apt Install: (error: command 'x86_64-linux-gnu-gcc' failed with exit status 1)
sudo apt-get install python3 python3-dev \
     build-essential libssl-dev libffi-dev \
     libxml2-dev libxslt1-dev zlib1g-dev \
pip3 Install:
sudo pip3 install cffi lxml spawn ccompiler


API model, 使用 C source code
op.c
#include <stdio.h>
#include <stdlib.h>
#include "op.h"

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

int sub (int a, int b)
{ return a-b;
}

int mul (int a, int b)
{ return a*b;
}

int divv (int a, int b)
{ return a/b;
}

int op (int num)
{
    int c=20,d=2;
    int e;
    int (*test)(int, int)=&add;

    switch(num)
    {
        case 1:
            test=add; break;
        case 2:
            test=sub; break;
        case 3:
            test=mul; break;
        case 4:
            test=divv; break;
    }
    e=test(c,d);
    printf("%d\n",e);
    return e;
}

op.h
#ifndef op_h_
#define op_h_
int add (int a, int b);
int sub (int a, int b);
int mul (int a, int b);
int divv (int a, int b);
int op(char num);
#endif

build.py
import cffi
  
  ffibuilder = cffi.FFI()
  
  ffibuilder.cdef("""
      int op(int num);
      """)
  
  ffibuilder.set_source('c_libop',  #name of the output C extension
      """ 
      #include "op.h"
      """,
      sources=['op.c'],
      libraries=['m'])    # on Unix, link with the math library
  
  if __name__ == '__main__':
      ffibuilder.compile(verbose=True)
會生成c_libop.cpython-36m-x86_64-linux-gnu.so和c_libop.o和op.o以及c_libop.c

test.py
import c_libop.lib as op
print(op.op(1))



ref:
1. Python Bindings: Calling C or C++ From Python
2. 掘金 - itisyanglv-1 - CFFI - ABI模式与API模式

沒有留言:

張貼留言