简体   繁体   English

如何安装与 Python.h 关联的库

[英]How to install the library associated with Python.h

I am working on calling C from Python.我正在从 Python 调用 C。 My "hello world" program references such functions as `PyUnicode_FromString', whose prototypes I believe are in the header file Python.h.我的“hello world”程序引用了诸如 `PyUnicode_FromString' 之类的函数,我相信它的原型在 header 文件 Python.h 中。 My system has the header file but seems to lack the associated library.我的系统有 header 文件,但似乎缺少相关的库。 I do not know what to install.我不知道要安装什么。 I already have done 'apt-get install python3-dev." Either I need to install the library or I if it is already there then I need to point to it when I compile. Here is my code:我已经完成了“apt-get install python3-dev”。要么我需要安装库,要么如果它已经存在,那么我需要在编译时指向它。这是我的代码:

#include <Python.h>
static PyObject* _hello_world(PyObject* self) {
    return PyUnicode_FromString("hello world");
}
static struct PyMethodDef methods[] ={
    {"hello_world", (PyCFunction)_hello_world, METH_NOARGS,},
    {NULL, NULL}
};

static struct  PyModuleDef module= {
    PyModuleDef_HEAD_INIT,
    "_hello",
    NULL,
    -1,
    methods
};

PyMODINIT_FUNC PyInit_hello(void) {
    return PyModule_Create(&module);
}

The library you're looking for is libpython , which should already be installed.您要查找的库是libpython ,它应该已经安装。 On Debian and Ubuntu, it's in the package libpython3.8 (or similar, depending on the version).在 Debian 和 Ubuntu 上,它位于 package libpython3.8 (或类似版本,取决于版本)中。

However, you should only have to worry about this if you're embedding Python in a native program.但是,只有在本机程序中嵌入 Python 时,您才应该担心这一点。 If you're extending Python by writing a module in C, I don't think you need libpython at all, and in any case distutils / setuptools should take care of all those details for you if you're building your module in the usual way as described in the documentation .如果您通过在 C 中编写模块来扩展 Python,我认为您根本不需要 libpython,无论如何,如果您以通常的方式构建模块, distutils / setuptools应该为您处理所有这些细节方式如文档中所述


Side note: it's generally not recommended these days to use the Python C/C++ API at all unless you have a very good reason.旁注:现在通常不建议使用 Python C/C++ API,除非您有充分的理由。 If you're just playing around and learning about how the internals of CPython work - fantastic, Carry on, and have fun!如果您只是在玩耍并了解 CPython 的内部工作原理 - 太棒了,继续玩,玩得开心!

But if you just have some C code that you want to call from a Python program, the best way to do this is generally either to call it with cffi or ctypes , or to write your extension module in Cython .但是,如果您只想从 Python 程序中调用一些 C 代码,那么最好的方法通常是使用cffictypes调用它,或者在Cython中编写扩展模块。 All of these options are easier and less likely to break with future versions of Python, and the first two have the added benefit of working well on other implementations of Python (ie PyPy ).所有这些选项都更容易并且不太可能与 Python 的未来版本中断,前两个具有额外的好处,可以在 Python(即PyPy )的其他实现上运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM