Подтвердить что ты не робот

Пример программы Cython как конвертер Python to C

Я нашел здесь и здесь, что можно использовать Cython для преобразования Python в C, но я не могу найти пошаговый пример. Скажем, у меня есть простая функция:

foo.pyx

cdef void foo(double* x):
   x[0] = 0.0

setup.py

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("foo.pyx")
)

тогда я запускаю: python setup.py build_ext --inplace, чтобы получить файлы foo.c и foo.so(и каталог сборки). Ну, я бы хотел использовать переведенную (надеюсь) функцию foo в main.c. Что следует поместить в файл main.c и как его скомпилировать, чтобы использовать функцию foo? Я использую gcc.

4b9b3361

Ответ 1

Вдали от эксперта c, но для меня, используя ubuntu, следующие работы:

main.c:

#include "foo_api.h"
#include <stdio.h>


int main(int argc, char *argv[]) {
     Py_Initialize();
     initfoo();
     import_foo();
     double arr[5] = {1,2,3,4,5};
     int i = 0;
     foo(arr);
     for(i = 0; i < 5; i++)
    {
      printf("%f\n", arr[i]);
    }
     Py_Finalize();
     return 0;
}

foo.pyx:

cdef public api  foo(double* x):
   x[0] = 0.0

Из того же каталога:

$ cython foo.pyx 

Тогда:

$ cc -I/usr/include/python2.7 -I/usr/include/x86_64-linux-gnu/python2.7   -o foo  *.c -lpython2.7 

Затем просто запустите.

$ ./foo
0.000000
2.000000
3.000000
4.000000
5.000000

Я использовал pkg-config --cflags python для получения флагов:

 $ pkg-config --cflags python
-I/usr/include/python2.7 -I/usr/include/x86_64-linux-gnu/python2.7 

Без вызова Py_Initialize (Инициализировать интерпретатор Python. В приложении, встраивающем Python, это нужно вызывать перед использованием любого другого Python/C API), вы получите:

Fatal Python error: PyThreadState_Get: no current thread
Aborted (core dumped)

Без initfoo() или import_foo() вы получите:

 Segmentation fault (core dumped)

Если вы не вызываете Py_Finalize:

Py_Initialize no-op при вызове во второй раз (без вызова Py_Finalize()).

Чтобы получить delorean пример из документации для запуска:

main.py:

#include "delorean_api.h"
#include <stdio.h>
Vehicle car;


int main(int argc, char *argv[]) {
     Py_Initialize();
     initdelorean();
     import_delorean();
     car.speed = atoi(argv[1]);
     car.power = atof(argv[2]);
     activate(&car);
     Py_Finalize();
     return 0;
}

delorean.pyx:

ctypedef public struct Vehicle:
    int speed
    float power

cdef api void activate(Vehicle *v):
    if v.speed >= 88 and v.power >= 1.21:
        print "Time travel achieved"
    else:
        print("Sorry Marty")

Процедура такая же, единственное изменение заключалось в том, что мне пришлось использовать ctypedef с конструкцией Vehicle, а также в основном или использовать, я использовал t struct Vehicle car; в основном:

$ cython delorean.pyx
$ cc  -I/usr/include/python2.7 -I/usr/include/x86_64-linux-gnu/python2.7   -o delorean  *.c -lpython2.7  
$ ./delorean 1 1
Sorry Marty
$ ./delorean 100 2
Time travel achieved

Вы также можете заставить его работать без использования Py_Initialize и т.д.

В foo.pyx вам просто нужно сделать функцию общедоступной:

cdef public  foo(double* x):
   x[0] = 0.0

Я добавил #include <python2.7/Python.h> только что импортированный foo.h в main.c и удалил Py_Initialize(); и т.д. Просто импортирование python.h не сработало бы для меня, но это может быть не для всех.

#include <python2.7/Python.h>
#include "foo.h"
#include <stdio.h>


int main(int argc, char *argv[]) {
     double arr[5] = {1,2,3,4,5};
     int i = 0;
     foo(arr);
     for(i = 0; i < 5; i++)
    {
      printf("%f\n", arr[i]);
    }

     return 0;
}

Компиляция была такой же:

$ cython foo.pyx 
$ cc -I/usr/include/python2.7 -I/usr/include/x86_64-linux-gnu/python2.7   -o foo  *.c -lpython2.7 
$ ./foo
0.000000
2.000000
3.000000
4.000000
5.000000

Если вы используете версию api, просто включите заголовок api или наоборот в соответствии с документами. Однако обратите внимание, что вы должны включать либо modulename.h, либо modulename_api.h в данном файле C, а не оба, иначе вы можете получить противоречивые двойные определения.

Чтобы сделать то же самое с примером delorean, мне пришлось использовать libc.stdio для печати строк, чтобы избежать ошибки сегментации:

from libc.stdio cimport printf

ctypedef public  struct Vehicle:
    int speed
    float power

cdef public void activate(Vehicle *v):
    if v.speed >= 88 and v.power >= 1.21:
        printf("Time travel achieved\n")
    else:
        printf("Sorry Marty\n")

главная:

#include <python2.7/Python.h>
#include <stdio.h>
#include "delorean.h"

Vehicle car;


int main(int argc, char *argv[]) {
     car.speed = atoi(argv[1]);
     car.power = atof(argv[2]);
     activate(&car);
     return 0;
}

Может потребоваться вернуть значения:

ctypedef public  struct Vehicle:
    int speed
    float power

cdef public  char* activate(Vehicle *v):
    if v.speed >= 88 and v.power >= 1.21:
        return  "Time travel achieved"
    return "Sorry Marty"

главная:

#include <python2.7/Python.h>
#include <stdio.h>
#include "delorean.h"

Vehicle car;

int main(int argc, char *argv[]) {
     car.speed = atoi(argv[1]);
     car.power = atof(argv[2]);
     printf("%s\n",activate(&car));
     return 0;
}