【发布时间】:2018-01-22 01:00:55
【问题描述】:
我今天开始wondering whether it is possible to save a python object for use in a C program,这个命题在阅读数小时后看起来很幼稚。这是一个可能的解决方法:
1。创建一个复杂的对象,该对象依赖于许多 python 库,其中包含我需要保留的数据。
2. 腌制复杂对象并将其放置在可以访问的地方。
3.定义compileme.py:
import pickle
thing = pickle.load(open('thing.pkl', 'r'))# an object with a method query(),
# which takes a numpy array as input
4。 cython --embed -o compileme.c compileme.py 生成脚本的 .c 版本。
5.定义main.c:
#include <stdio.h>
#include//(A) something from compileme
int main(void) {
input = //(B) query takes a numpy array in python. Define something palatable.
double result = thing.query(input);
printf("%d", result);
}
6。使用所有正确的链接正确编译 main.c。
我不清楚这个基本的解决策略是否合理,我有一些担忧:
-
thing是这里甚至没有提到的库中的一个类,所以它的query()方法依赖于外部 python。如何确保相关部分也被编译和链接? - 我应该如何在我的
main.c中包含compileme以便在那里可以访问thing? (代码中的位置 (A)) - 如何在此处适当地定义
thing方法的输入?我需要使用compileme.c中定义的众多类型之一吗? (代码中的位置 (B)) - 如何使用正确的链接编译
main.c? - 在执行所有这些操作时,似乎我必须包含对来自
python-dev包的python 头文件的引用。为了清楚起见,我实际上并没有通过这样做来包括口译员,对吗?
以下是我在搜索过程中发现的一些资源,证明可以将简单的 python 脚本编译为可执行的编译 C 程序:Compile main Python program using Cython http://masnun.rocks/2016/10/01/creating-an-executable-file-using-cython/
这是一些相关的 cython 文档: http://cython.readthedocs.io/en/latest/src/reference/compilation.html
【问题讨论】:
-
一般这种方式对外保存对象是为了持久化数据;您通常无法从对象中序列化逻辑。您可以将数据导入其他进程,然后使用该程序中定义的方法将其反序列化回类/对象中。
-
@EliKorvigo,那 Py_Initialize() 东西实际上不是调用了 python 运行时环境吗?我想避免这种情况,因为我的嵌入式应用程序没有 python。
-
@Joe 是的,pickle 通常用于从 python 中保存并读回 python。这里的想法是我会编译一些封装逻辑的东西,而泡菜封装对象设置,部分逻辑是在启动时读取设置。
-
如果不链接到 Python 解释器,您将无法做到这一点。
标签: python c compilation cython