python - 从 C 调用 python hello world 函数,解析字符串参数

标签 python c python-2.7

我使用了this answer中的代码创建以下文件

callpython.c

#include </usr/include/python2.7/Python.h>

int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyString_FromString(argv[1]);
    /* Error checking of pName left out */
    //fprintf(stderr,"pName is %s\n", pName);
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");
    //PySys_SetArgv(argc, argv);

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyInt_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                } 
                /* iValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
                //PyTuple_SetItem(pArgs, i, argv[i + 3]);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}

我在与 helloWorld.py 相同的目录中创建了另一个文件。这个Python脚本的内容是

def helloworldFunc(a):
    print 'Hello '+str(a)

我编译并运行 callpython.c 如下

 g++ -o callpython callpython.c -lpython2.7 -lm -L/usr/lib/python2.7/config && ./callpython helloworld helloworldFunc world

它不是打印“Hello world”,而是打印“Hello 0”

为什么它不将 python 函数参数解析为字符串?

最佳答案

示例代码将参数解析为整数,假设您传递了一个字符串。 atoi("world") 返回 0,这就是您得到的整数:

/* Create tuple of the correct length for the arguments. */
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
   /* Convert each C argv to a C integer, then to a Python integer. */
    pValue = PyInt_FromLong(atoi(argv[i + 3]));
    if (!pValue) {
        Py_DECREF(pArgs);
        Py_DECREF(pModule);
        fprintf(stderr, "Cannot convert argument\n");
        return 1;
    } 
    /* iValue reference stolen here: */
    /* Store the Python integer in the tuple at the correct offset (i) */
    PyTuple_SetItem(pArgs, i, pValue);
}

将转换行更改为以下内容以处理任何字符串:

pValue = PyString_FromString(argv[i + 3]);

关于python - 从 C 调用 python hello world 函数,解析字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50441365/

相关文章:

c++ - 如何在 SWIG 中为 C++ 创建模板函数?

python panda通过删除重复项加入动态列

c++ - 如何理解这个C声明代码?

python - 传入字符串作为参数而不将其视为原始字符串

Python:PyDateTime_FromTimestamp 的用法

c - 为什么 fopen() 或 open() 使用 errno 而不是只返回错误代码?

python - IO错误 : [Errno 0] Error when running python code using visual studio code

python - imshow 3D? ( python /Matplotlib)

python - PYGAME:碰撞无法正常工作。播放器和平台表现不佳。帮助,这里是python的新手

python - 使用 wnck (python) 确定事件窗口/应用程序失败