python 嵌入到 C 中:将 python 脚本定义为 C 字符串?

python embedding in C : define the python script as a C string?

我想在 C 中调用以下 python 脚本:

#!/usr/bin/python2.7

import parser

def evaluate(text):
   code = parser.expr(text).compile()
   return eval(code)

如下页 https://docs.python.org/2/extending/embedding.html 所述,我可以使用文件的密码(路径)从 C 调用此脚本。

但是,我想知道是否可以通过直接在 C 字符串上调用 python 来定义脚本来不加载脚本。

例如,我想说我输入了:

#define PYTHON_SCRIPT ((char*)(\      
  import parser\  
  \                    
  def evaluate(text):\   
    code = parser.expr(text).compile()\  
    return eval(code)\ 
  ))

是否可以直接对该字符串调用 python 解释器?

确实,我知道我需要将文本作为变量传递,但我不能使用这个 Pyrun_SimpleString 函数,而且我找不到可以回答这个问题的东西。

看看 Weave,它允许您直接在 Python 代码中包含 C 代码。

如评论中所述,没有 Pyrun_SimpleStringhere 涵盖了如何从 C 执行 Python 函数。一种方法:

  1. 使用 Py_CompileString
  2. 编译您的脚本
  3. 为 globals/locals 创建字典。
  4. 使用 PyDict_GetItemString(name)
  5. 从全局字典中提取函数
  6. 使用 PyArg_ParseTuple
  7. 构建参数元组
  8. 使用PyObject_CallFunction执行你的函数对象。