首页 > 解决方案 > 在 python 和 C++ 之间传递变量(嵌入,而不是扩展)

问题描述

我才刚开始,所以请不要贴我 200 行代码来转换 int。我需要用尽可能少的晦涩命令来保持简单。

我花了几个小时试图找到一个尽可能入门的例子,但什么也没找到。我尝试了无数的 PyArg_ParseTuple、PyArg_Parse、Py_BuildValue 等等。可能语法错误,但所有文档都没有示例。在一些本应极其微不足道的事情之后花费数小时,我感到非常沮丧。

我只是想在 C++ 代码中嵌入一个小的 python 函数。为了使事情尽可能简单,我只想将一个名为 a1 的 C int 传递给 python 函数,将其添加到 b1,获取返回值并使用 cout 从 C++ 打印它。

所以:

PyObject *pmod1;
int a1 = 20; 
int cresult = 0;
int b1 = 0;

Py_Initialize();
pmod1 = PyImport_ImportModule("usermod");

(GAP HERE)

std::cout << cresult << " " << a1 << " " << b1;

Py_Finalize();

usermod.py 是:

pythb1 = 5;

def ThisFunc(a,b):
  result = a+b
  return result

就这样。我想将 a1 C-int 传递给 Thisfunc a,将 pythb1 传递给 b,然后将“结果”赋值给“cresult”,并用 cout 打印它。我还想从 python 函数中读取 pythb1 以将该值放入 b1 中。

所以 cout 输出将是: 25 20 5

有人可以提供最直接最简单的代码吗?我需要填补 C++ 代码中的空白......

在我尝试过的(许多)事情之间: long a1(PyLong_AsLong(pmod3));

其中 pmod3 是一个 python 对象。这会使程序崩溃,没有错误消息。

一次又一次地编辑:我设法靠自己完成了一些事情。我能够改编我在书中找到的一个例子,否则我在互联网上找不到任何有用的东西......

并完成,经过一百万次尝试和编辑。这编译。我不知道它是否应该如何工作,但它可以满足我的需求。

这也很棘手,因为如果您将变量的名称设置错误,编译器不会给出任何错误消息,它的行为不像 C++ 代码。

PyObject *pmod, *pdict, *pvar, *presult, *pa1;
long a1 = 20, b1, cresult; 

Py_Initialize();

pmod = PyImport_ImportModule("usermod");
pdict = PyModule_GetDict(pmod);
pvar = PyRun_String("pythb1", Py_eval_input, pdict, pdict); // this reads the pthb1 set in the python script, and puts it in pvar object

if(PyLong_Check(pvar)){
  b1 = (PyLong_AsLong(pvar)); // this copies the python object pthb1/pvar into b1 C long, it seems there are only long types in python
}

pa1 = (PyLong_FromLong(a1)); // this creates a python object from a C long

PyObject_SetAttrString(pmod, "X1", pa1);
PyObject_SetAttrString(pmod, "X2", pvar);
presult = PyRun_String("ThisFunc(X1,X2)", Py_eval_input, pdict, pdict);

if(PyLong_Check(presult)){
  cresult = (PyLong_AsLong(presult)); 
}

std::cout << cresult << " " << a1 << " " << b1 << std::endl;

Py_DECREF(pmod); // cleaning
Py_DECREF(pvar);
Py_DECREF(presult);
Py_DECREF(pa1);

Py_Finalize();

输出:25 20 5,完全符合预期。

所以绝对可以做到。出于某种神秘的原因,没有任何例子。

我只是希望所有这些都有更多更好的文档......

标签: pythonc++embedding

解决方案


绝对不是正确的方法,但您可以使用大多数解释语言从大多数语言中做到这一点:

#include <stdio.h>

#define RESULT_MAX_LENGTH 256

int main()
{
  int a = 5;
  int b = 10;

  char cmd[256];
  sprintf(cmd, "python -c \"import usermod; print(usermod.Thisfunc(%d, %d))\"", a, b);

  //printf("%s", cmd);

  FILE * fp = popen(cmd, "r");

  char result[RESULT_MAX_LENGTH];
  while (fgets(result, RESULT_MAX_LENGTH, fp) != NULL)
    printf("%s", result);

  return 0;
}

对于在 C 中嵌入 Python 的正确方法,Daniel Dearlove 是对的,请按照此处的说明进行操作:https ://docs.python.org/3/extending/embedding.html


推荐阅读