python - 我们可以在 Python 中使用 C 代码吗?

标签 python c linux compiler-construction

我知道 Python 提供了一个 API,所以你可以在 C 代码中调用 Python 解释器,但我想要的是相反的。

我的程序需要使用一些C API,所以代码必须用C编写。但我也想用Python打包程序。这意味着我想在 Python 中调用那些 C 函数或可执行文件。这可能吗?

如果我希望 C 代码成为一个库,这意味着我将它与 #include 和可能在 Python 中的 *.o 链接一起使用,该怎么做它?那可能吗?如果我把C代码写成可执行文件,也就是变成一个命令,我可以直接在Python中调用吗?

另外,听说Python代码可以编译,是不是说不用源文件也可以执行代码?输出文件是二进制文件吗?它会提高性能吗?

最佳答案

I want to invoke those C function or executables in python. Is that possible.

是的,您可以编写可作为模块导入 Python 的 C 代码。 Python 调用这些扩展模块。您可以直接从 Python 调用它,documentation 中的一个示例:

Python 代码

import example
result = example.do_something()

C 代码

static PyObject * example(PyObject *self)
{
    // do something
    return Py_BuildValue("i", result);
}

If I want the C code to be a library, which means I use it with #include and linkage of the *.o likely in python, how to do it or is that possible.

您将其构建为共享库 *.dll*.so 您还可以调查使用 distutils 分发您的模块。

If I write the C code into executable, which means it becomes a command, can I invoke it in python directly?

如果你写一个 *.exe 那么你正在做相反的事情(调用 Python from C )。您选择的方法(exe 与共享库)取决于您是想要“带有一些 Python 的 C 程序”还是“带有一些 C 的 Python 程序”

Also, I heard that python code can be compiled, does that mean we can execute the code without the source file? Are the output files binary files? Does it improve performance?

Python 会在您运行时读取 *.py 文件并编译成 *.pyc 字节码 文件。然后字节码在 Python 虚拟机中运行。这意味着“第二次执行相同的文件更快,因为可以避免从源代码到字节码的重新编译。”(来自 Python 词汇表)所以如果你还没有编辑你的 *.py 文件,它将运行 *.pyc。您可以分发没有 *.py 文件的 *.pyc 文件,但它们没有加密并且可以进行逆向工程。

关于python - 我们可以在 Python 中使用 C 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18762621/

相关文章:

linux - 纳斯姆 x86_64 : Why can't I write and read from the same file?

python - 如何更快地处理nparrays

python - Bluemix Python App启动失败

c - 8051单片机设置去年

c链表从txt文件读取

linux - smem如何计算RSS、USS和PSS?

linux - snmp 服务无法在 Linux 中正确运行我的程序

将 'None' 字符串转换为 None 的 Pythonic 方式

python - 来自输入函数的 NameError

C 到 MIPS 的转换。数组加载字偏移量?