从调用C / C ++蟒蛇方法,并提取其返回值 [英] Calling a python method from C/C++, and extracting its return value

查看:154
本文介绍了从调用C / C ++蟒蛇方法,并提取其返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打电话是从C的Python模块,我有一些preliminary code做,在定义自定义函数,但它只是打印输出到标准输出。

I'd like to call a custom function that is defined in a python module from C. I have some preliminary code to do that, but it just prints the output to stdout.

mytest.py

import math

def myabs(x):
    return math.fabs(x)

TEST.CPP

#include <Python.h>

int main() {
    Py_Initialize();
    PyRun_SimpleString("import sys; sys.path.append('.')");
    PyRun_SimpleString("import mytest;");
    PyRun_SimpleString("print mytest.myabs(2.0)");
    Py_Finalize();

    return 0;
}

我怎么能提取的返回值成C双,并在C使用它?

How can I extract the return value into a C double and use it in C?

推荐答案

由于使用PyRun_SimpleString似乎是一个坏主意之前解释。

As explained before, using PyRun_SimpleString seems to be a bad idea.

您一定要使用由C-API提供的方法(http://docs.python.org/c-api/)。

You should definitely use the methods provided by the C-API (http://docs.python.org/c-api/).

阅读介绍是做了解它的工作方式的第一件事。

Reading the introduction is the first thing to do to understand the way it works.

首先,你必须了解的PyObject是对于C API的基本对象。它可以重新present任何种类的巨蟒基本类型(字符串,浮点,整数,...)。

First, you have to learn about PyObject that is the basic object for the C API. It can represent any kind of python basic types (string, float, int,...).

许多功能存在,例如转换Python字符串为char *或PyFloat翻番。

Many functions exist to convert for example python string to char* or PyFloat to double.

首先,导入你的模块:

PyObject* myModuleString = PyString_FromString((char*)"mytest");
PyObject* myModule = PyImport_Import(myModuleString);

然后得到一个参考给你的函数:

Then getting a reference to your function :

PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"myabs");
PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(2.0));

然后让你的结果是:

Then getting your result :

PyObject* myResult = PyObject_CallObject(myFunction, args)

和又回到了双:

double result = PyFloat_AsDouble(myResult);

您显然应该检查错误(由Mark Tolonen给参见链接)。

You should obviously check the errors (cf. link given by Mark Tolonen).

如果您有任何问题,不要犹豫。祝你好运。

If you have any question, don't hesitate. Good luck.

这篇关于从调用C / C ++蟒蛇方法,并提取其返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆