【问题标题】:Using Cython as a C wrapper [closed]使用 Cython 作为 C 包装器 [关闭]
【发布时间】:2018-03-08 23:10:44
【问题描述】:

Python 文档中的示例描述了如何同时包装结构、处理内存分配和函数。我也不明白 setup.py 文件是如何编译我的 C 代码的。有人可以给我一个简单的例子,说明如何使用 Cython 和 gcc 编译器来包装,打个招呼的世界程序?

【问题讨论】:

标签: c python-2.7 cython wrapper compiler-optimization


【解决方案1】:

您需要一个 C 文件来包含 C 函数 (base_hello.c),一个 C 头文件来包含这些 C 函数的声明 (base_hello.h),以及一个 cython 文件来告诉 cython 如何转换这些 C 函数进入python函数(hello.pyx)。以下是它们各自包含的内容:

base_hello.c

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

int print_hello_world(int N_prints){

    for (int i=0; i<N_prints; i++){
        printf("%i Hello World\n",i);
    }

    return 2*N_prints;
}

base_hello.h

int print_hello_world(int N_prints);

hello.pyx

cdef extern from "base_hello.h":
    int print_hello_world(int N_prints);

def run_print_hello_world(N_prints):
    return print_hello_world(N_prints)

然后你需要将 base_hello.c 编译成一个对象文件,然后将 hello.pyx 文件编译成一个共享对象,然后可以将它导入到 python 中。基本上 hello.pyx 告诉 Cython 如何将 C 函数转换为 python 函数。您可以使用根据 cython 文档创建的 setup.py 编译这些文件,也可以使用类似于以下编译命令的东西来编译这些文件,您肯定想在其中更改 python 实例的路径:

cython -v -2 hello.pyx
cc -shared -fPIC -I"/Users/michael/miniconda2/include/python2.7" -o hello.so hello.c base_hello.c

为了测试它是否有效,这里有一个简单的测试脚本 test_hello.py。

test_hello.py

import hello

for i in range(4):
    print 'TESTING %i PRINTS'%i
    hello.run_print_hello_world(i)

运行“python test_hello.py”应该会输出以下内容:

TESTING 0 PRINTS
TESTING 1 PRINTS
0 Hello World
TESTING 2 PRINTS
0 Hello World
1 Hello World
TESTING 3 PRINTS
0 Hello World
1 Hello World
2 Hello World

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2013-09-11
    • 2011-03-25
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多