python - 使用 Cython 创建 C 包装器 - Python

标签 python c ubuntu boost-python cython

我一直在想办法包装下面的 C 函数 = compress.c , compress.h .

我尝试按照教程进行操作,但是在创建了 .pxd 文件之后我不知道该怎么做:|

据我了解,这是我应该拥有的 pxd 文件

cdef extern from "compress.h":

    size_t compress(void *s_start, void *d_start, size_t s_len)
    size_t decompress(void *s_start, void *d_start, size_t s_len, size_t d_len)
    uint32_t checksum32(void *cp_arg, size_t length)

在此之后我不知道该做什么 :|


帮助会很棒的家伙! =)


编辑:

得到这个错误

~/essentials/pylzjb# gcc -I /usr/include/python2.6 -shared -o pylzjb.so pylzjb.c compress.c

/usr/bin/ld: /tmp/ccQLZTaG.o: relocation R_X86_64_32S against `_Py_NoneStruct' 
can not be used when making a shared object; recompile with -fPIC
/tmp/ccQLZTaG.o: could not read symbols: Bad value
collect2: ld returned 1 exit status

还是谢谢=)

最佳答案

编写一个 .pyx 文件来实现调用 C 函数的包装器? 我认为最困难的部分可能是缓冲区处理......

pylzjb.pyx 可能如下所示(请注意您的 .pxd 是内联的):

cdef extern from "compress.h":
    size_t compress(void *s_start, void *d_start, size_t s_len)

from stdlib cimport *

def cmpr(bytes s):
    cdef size_t n = len(s)
    cdef unsigned char *dst = <unsigned char *> malloc(n * sizeof(unsigned char))
    try:
        m = compress(<unsigned char *> s, dst, n)
        ret = [dst[i] for i from 0 <= i < m]
    finally:
        free(dst)
    return ret

编译:

cython -I. pylzjb.pyx
gcc -I /usr/include/python2.5 -shared -o pylzjb.so pylzjb.c compres.c

并尝试使用 with

import pylzjb
pylzjb.cmpr('asfd')

关于python - 使用 Cython 创建 C 包装器 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3352285/

相关文章:

c - 使用指向结构的双指针和结构指针重新分配动态二维数组

c - gcc 优化对共享库操作的影响

python - DeprecationWarning : Using or importing the ABCs from 'collections' instead of fr om 'collections.abc' is deprecated, 在 3.8 中它将停止工作

c - 生成-1.5到1.5之间的10个随机数并将它们写入ran.dat文件中

linux - specflow.exe - 'libhostpolicy.so' 未找到

python - 使用 setuputils 安装带有 Upstart 服务的 Python 包

python - Ubuntu : Schedule python scripts using Fork

python - 自定义 matplotlib 图形的默认工具栏图标图像

python - 如何使 fcluster 返回与 cut_tree 相同的输出?

python - Pandas:通过属性 out=agg 复制 SAS 过程