gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:26:33 25 4
gpt4 key购买 nike

抱歉,如果这太含糊了。我最近在阅读 python 的 list.sort() 方法,并了解到它是出于性能原因用 C 语言编写的。

我假设 python 代码只是将一个列表传递给 C 代码,C 代码将一个列表传回,但是 python 代码如何知道将它传递到哪里或者 C 给它正确的数据类型,并且C 代码如何知道给定的数据类型?

最佳答案

Python 可以在 C/C++ 中扩展(更多信息 here)

这基本上意味着您可以像这样包装一个 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 */
};

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

关于python - 编程语言如何调用用另一种语言编写的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21261458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com