C / C ++ من بيثون (CFFI ، pybind11)

رئيسي

نواصل موضوع كيفية استدعاء C / C ++ من Python3 . الآن نستخدم مكتبات cffi و pybind11 . تمت مناقشة الطريقة من خلال ctypes في مقال سابق.


C


مكتبة اختبار لشرح العمل مع المتغيرات العالمية والهياكل والوظائف مع الوسائط من أنواع مختلفة.
test.h


typedef struct test_st_s test_st_t; extern int a; extern double b; extern char c; int func_ret_int(int val); double func_ret_double(double val); char *func_ret_str(char *val); char func_many_args(int val1, double val2, char val3, short val4); test_st_t *func_ret_struct(test_st_t *test_st); struct test_st_s { int val1; double val2; char val3; }; 

test.c


 #include <stdio.h> #include <stdlib.h> #include "test.h" int a = 5; double b = 5.12345; char c = 'X'; int func_ret_int(int val) { printf("C get func_ret_int: %d\n", val); return val; } double func_ret_double(double val) { printf("C get func_ret_double: %f\n", val); return val; } char * func_ret_str(char *val) { printf("C get func_ret_str: %s\n", val); return val; } char func_many_args(int val1, double val2, char val3, short val4) { printf("C get func_many_args: int - %d, double - %f, char - %c, short - %d\n", val1, val2, val3, val4); return val3; } test_st_t * func_ret_struct(test_st_t *test_st) { if (test_st) { printf("C get test_st: val1 - %d, val2 - %f, val3 - %c\n", test_st->val1, test_st->val2, test_st->val3); } return test_st; } 

المكتبة هي نفسها تمامًا كما في المقالة ctypes .


CFFI


هذه مكتبة للعمل حصريًا مع C. من وصف هذه المكتبة:


تفاعل مع أي كود C تقريبًا من Python

تم العثور على بعض هذا تقريبا.


للتجربة ، تم استخدام الإصدار 1.12.3 ، يمكنك أن تقرأ عنها هنا .


قليلاً عن هذه المكتبة بكلمتين ، تقوم CFFI بإنشاء ارتباطها أعلى مكتبتنا وتجميعها في مكتبة سنعمل معها.


تركيب


pip3 تثبيت cffi


جمعية


النص البرمجي للبناء الذي سيجمع الرابط حول مكتبتنا.


build.py


 import os import cffi if __name__ == "__main__": ffi = cffi.FFI() #    PATH = os.getcwd() # test.h     #      build.py with open(os.path.join(PATH, "src/c/test.h")) as f: ffi.cdef(f.read()) ffi.set_source("_test", #    cffi,   _ #  test.h,     _test '#include "../src/c/test.h"', #   libtest.so (  ) #  _test.cpython-36m-x86_64-linux-gnu.so ( CFFI) libraries=[os.path.join(PATH, "lib/test"), "./test"], library_dirs=[PATH, 'objs/'], ) #  _test   lib ffi.compile(tmpdir='./lib') 

الثعبان


مثال على العمل مع C من Python من خلال CFFI :


 from cffi import FFI import sys import time #    _test sys.path.append('.') sys.path.append('lib/') sys.path.append('../../lib/') #   import _test ### ## C ### print("CFFI\n") print("C\n") start_time = time.time() ## #    ## print('  :') print('ret func_ret_int: ', _test.lib.func_ret_int(101)) print('ret func_ret_double: ', _test.lib.func_ret_double(12.123456789)) #     cdata   ,     . print('ret func_ret_str: ', _test.ffi.string(_test.lib.func_ret_str('Hello!'.encode('utf-8'))).decode("utf-8")) print('ret func_many_args: ', _test.lib.func_many_args(15, 18.1617, 'X'.encode('utf-8'), 32000).decode("utf-8")) ## #    ## print('\n  :') print('ret a: ', _test.lib.a) #   . _test.lib.a = 22 print('new a: ', _test.lib.a) print('ret b: ', _test.lib.b) print('ret c: ', _test.lib.c.decode("utf-8")) ## #    ## print('\n  :') #      test_st = _test.ffi.new("test_st_t *") test_st.val1 = 5 test_st.val2 = 5.1234567 test_st.val3 = 'Z'.encode('utf-8') ret = _test.lib.func_ret_struct(test_st) #    C print('ret val1 = {}\nret val2 = {}\nret val3 = {}'.format(ret.val1, ret.val2, ret.val3.decode("utf-8"))) #   print("--- %s seconds ---" % (time.time() - start_time)) 

للعمل مع رمز C ++ ، تحتاج إلى كتابة ارتباط C له. توضح المقالة حول الطريقة من خلال ctypes كيفية القيام بذلك. الرابط أدناه.


إيجابيات وسلبيات CFFI


الايجابيات :


  • بناء جملة بسيط عند استخدامه في بيثون
  • لا حاجة لإعادة ترجمة مكتبة المصدر

سلبيات :


  • ليس التجميع مريحة ، تحتاج إلى تسجيل المسارات إلى جميع ملفات رأس والمكتبات
  • يتم إنشاء مكتبة أكثر ديناميكية ، والتي تستخدم الأصل
  • لا يدعم التوجيهات التالية:
     #ifdef __cplusplus extern "C" { #endif ... #ifdef __cplusplus } #endif 

     #ifndef _TEST_H_ #define _TEST_H_ ... #endif /* _TEST_H_ */ 

pybind11


على النقيض من ذلك ، تم تصميم pybind11 خصيصًا للعمل مع C ++ . تم استخدام الإصدار 2.3.0 للتجربة ، يمكنك أن تقرأ عنها هنا . إنها لا تجمع مصادر C ، لذلك قمت بترجمتها إلى مصادر C ++.


تركيب


pip3 تثبيت pybind11


جمعية


نحن بحاجة إلى كتابة نص بناء لمكتبتنا.
build.py


 import pybind11 from distutils.core import setup, Extension ext_modules = [ Extension( '_test', #    pybind11 ['src/c/test.cpp'], #     include_dirs=[pybind11.get_include()], #     pybind11 language='c++', #   extra_compile_args=['-std=c++11'], #  ++11 ), ] setup( name='_test', #    pybind11 version='1.0.0', author='djvu', author_email='djvu@inbox.ru', description='pybind11 extension', ext_modules=ext_modules, requires=['pybind11'], #    pybind11 package_dir = {'': 'lib'} ) 

نقوم بتنفيذها:


 python3 setup.py build --build-lib=./lib 

C ++


في مصدر المكتبة ، تحتاج إلى إضافة:


  • ملف رأس pybind11
     #include <pybind11/pybind11.h> 
  • الماكرو الذي يسمح لنا بتحديد وحدة بيثون
     PYBIND11_MODULE(_test, m) 
  • مثال الماكرو لمكتبة اختبار:

 namespace py = pybind11; // _test    PYBIND11_MODULE(_test, m) { /* *   */ m.def("func_ret_int", &func_ret_int); m.def("func_ret_double", &func_ret_double); m.def("func_ret_str", &func_ret_str); m.def("func_many_args", &func_many_args); m.def("func_ret_struct", &func_ret_struct); /* *    */ m.attr("a") = a; m.attr("b") = b; m.attr("c") = c; /* *  */ py::class_<test_st_t>(m, "test_st_t") .def(py::init()) //  .    ,    Python //       C,  C++  (   C     ++   ) .def_readwrite("val1", &test_st_t::val1) //   .def_readwrite("val2", &test_st_t::val2) .def_readwrite("val3", &test_st_t::val3); }; 

الثعبان


مثال على العمل مع C من Python عبر pybind11 :


 import sys import time #    _test sys.path.append('lib/') #   import _test ### ## C ### print("pybind11\n") print("C\n") start_time = time.time() ## #    ## print('  :') print('ret func_ret_int: ', _test.func_ret_int(101)) print('ret func_ret_double: ', _test.func_ret_double(12.123456789)) #     cdata   . print('ret func_ret_str: ', _test.func_ret_str('Hello!'.encode('utf-8'))) print('ret func_many_args: ', _test.func_many_args(15, 18.1617, 'X'.encode('utf-8'), 32000)) ## #    ## print('\n  :') print('ret a: ', _test.a) #   . _test.a = 22 print('new a: ', _test.a) print('ret b: ', _test.b) print('ret c: ', _test.c) ## #    ## print('\n  :') #      _test_st = _test.test_st_t() #print(dir(_test_st)) _test_st.val1 = 5 _test_st.val2 = 5.1234567 _test_st.val3 = 'Z'.encode('utf-8') ret = _test.func_ret_struct(_test_st) #    C print('ret val1 = {}\nret val2 = {}\nret val3 = {}'.format(ret.val1, ret.val2, ret.val3)) #   print("--- %s seconds ---" % (time.time() - start_time)) 

إيجابيات وسلبيات pybind11


الايجابيات :


  • بناء جملة بسيط عند استخدامه في بيثون

سلبيات :


  • تحتاج إلى تحرير مصادر C ++ ، أو كتابة ارتباط لهم
  • من الضروري جمع المكتبة اللازمة من المصدر

يبدأ متوسط ​​وقت تنفيذ الاختبار في كل طريقة بـ 1000:


  • ctypes: - 0.0004987692832946777 seconds ---
  • CFFI: - 0.00038521790504455566 ثانية ---
  • pybind: - 0.0004547207355499268 ثانية ---

+ ، - لأن النتائج كانت مختلفة قليلاً في كل مرة. بالإضافة إلى ذلك ، فقد قضيت وقتًا في الطباعة ، وكنت كسولًا جدًا لإيقاف تشغيله (خذ هذا الوقت بثبات ، لأنه سيكون تقريبًا في جميع الاختبارات). ولكن لا يزال ، هناك فرق زمني في استدعاءات الوظائف والحصول على النتائج منها.


مراجع


Source: https://habr.com/ru/post/ar468099/


All Articles