gpt4 book ai didi

python - 将 python 代码转换为共享对象

转载 作者:行者123 更新时间:2023-12-02 08:15:09 32 4
gpt4 key购买 nike

我想从 python 模块准备一个共享对象 (.so)。我遇到了 Cython,它 a) 首先将 *.pyx 模块转换为 *.c 代码,b) 然后这个 *.c 代码将转换为共享对象 (.so)。 Cython 的所有示例都说明了如何将这个 .so 导入到 python 中。

但是,我有兴趣从 C 代码中读取这个共享对象。当我编写示例 C 代码来读取 .so 时,它会抛出一个错误,指出 .pyx 中实际存在的方法并不存在于 .so 对象中。

我想知道a) 是否可以从不同语言(例如 C)从 Cython 读取共享对象b) 并且,如果上述陈述为 True,我必须在代码中进行哪些更改才能从 C 读取共享对象。

谢谢

Python 代码(另存为 square_number.pyx)

def square_me(int x):
return x * x

Cython 对应的 setup.py 文件

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

setup(
ext_modules=cythonize("square_number.pyx"),
)

用于将上述 .pyx 转换为 .So 的命令行语句(通过 cython)

python setup.py build_ext --inplace

这将在同一文件夹中创建一个 square_number.so 。现在,我将其重命名为 libSquareNumber.so

用于读取.so的C代码

#include<stdio.h>

int main(int argc,char *argv[])
{
int result;

result=square_me(2);

printf("Sum of entered numbers = %d\n",result);

return 0;
}

当我尝试从上述命令编译和构建可执行文件时,出现错误

C代码的编译:

gcc -L/home/USRNAME/work/cython-codes/squaring/ -Wall -o test so_reader_in_c.c -lSquareNumber

错误

so_reader_in_c.c: In function ‘main’:
so_reader_in_c.c:11:4: warning: implicit declaration of function ‘square_me’ [- Wimplicit-function-declaration]
result=square_me(2);
^
/tmp/ccE5vIOH.o: In function `main':
so_reader_in_c.c:(.text+0x1a): undefined reference to `square_me'
collect2: error: ld returned 1 exit status

最佳答案

将 square_number.pyx 更改为:

cdef public int square_me(int x):
return x * x

运行“setup.py”后,它将生成头文件“square_number.h”。将其包含在您的主应用程序中。见下文:

将您的“主要”功能更改为:

#include <Python.h>
#include "square_number.h"

int main()
{
Py_Initialize();
initsquare_number();
printf("%d",square_me( 4 ) );
Py_Finalize();
return 0;
}

编译时请确保链接到 libpython.so 和 libsquare_number.so您还需要通过向 gcc 提供 -I 标志来处理“Python.h”的包含目录搜索路径。

有关更多信息,请参阅:http://docs.cython.org/src/userguide/external_C_code.html

关于python - 将 python 代码转换为共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25138402/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com