编程语言如何调用用另一种语言编写的代码?

Igg*_*boo 6 c python language-agnostic cpython

对不起,如果这太模糊了.我最近阅读了有关python的list.sort()方法的内容,并且因为性能原因读到它是用C语言编写的.

我假设python代码只是将列表传递给C代码并且C代码传回一个列表,但是python代码如何知道传递它的位置或者C给它正确的数据类型,以及如何C代码知道它给出的数据类型是什么?

Jak*_*yer 6

Python可以用C/C++扩展(更多信息在这里)

它基本上意味着你可以像这样包装一个C模块

#include "Python.h"

// Static function returning a PyObject pointer
static PyObject *
keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds) 
// takes self, args and kwargs.
{ 
    int voltage;
    // No such thing as strings here. Its a tough life.
    char *state = "a stiff";
    char *action = "voom";
    char *type = "Norwegian Blue";
    // Possible keywords
    static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

    // unpack arguments
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
                                     &voltage, &state, &action, &type))
        return NULL;
    // print to stdout
    printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
           action, voltage);
    printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);

    // Reference count some None.
    Py_INCREF(Py_None);
    // return some none.
    return Py_None;
}
// Static PyMethodDef
static PyMethodDef keywdarg_methods[] = {
    /* The cast of the function is necessary since PyCFunction values
     * only take two PyObject* parameters, and keywdarg_parrot() takes
     * three.
     */
    // Declare the parrot function, say what it takes and give it a doc string.
    {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
     "Print a lovely skit to standard output."},
    {NULL, NULL, 0, NULL}   /* sentinel */
};
Run Code Online (Sandbox Code Playgroud)

使用Python头文件,它将定义和理解C/C++代码中的入口点和返回位置.