# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # python-doc bot, 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.15\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-11-01 00:10+0000\n" "PO-Revision-Date: 2025-09-16 00:00+0000\n" "Last-Translator: python-doc bot, 2025\n" "Language-Team: German (https://app.transifex.com/python-doc/teams/5390/de/)\n" "Language: de\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../../extending/extending.rst:8 msgid "Using the C API: Assorted topics" msgstr "" #: ../../extending/extending.rst:10 msgid "" "The :ref:`tutorial ` walked you through creating a C " "API extension module, but left many areas unexplained. This document looks " "at several concepts that you'll need to learn in order to write more complex " "extensions." msgstr "" #: ../../extending/extending.rst:19 msgid "Errors and Exceptions" msgstr "" #: ../../extending/extending.rst:21 msgid "" "An important convention throughout the Python interpreter is the following: " "when a function fails, it should set an exception condition and return an " "error value (usually ``-1`` or a ``NULL`` pointer). Exception information " "is stored in three members of the interpreter's thread state. These are " "``NULL`` if there is no exception. Otherwise they are the C equivalents of " "the members of the Python tuple returned by :meth:`sys.exc_info`. These are " "the exception type, exception instance, and a traceback object. It is " "important to know about them to understand how errors are passed around." msgstr "" #: ../../extending/extending.rst:30 msgid "" "The Python API defines a number of functions to set various types of " "exceptions." msgstr "" #: ../../extending/extending.rst:32 msgid "" "The most common one is :c:func:`PyErr_SetString`. Its arguments are an " "exception object and a C string. The exception object is usually a " "predefined object like :c:data:`PyExc_ZeroDivisionError`. The C string " "indicates the cause of the error and is converted to a Python string object " "and stored as the \"associated value\" of the exception." msgstr "" #: ../../extending/extending.rst:38 msgid "" "Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an " "exception argument and constructs the associated value by inspection of the " "global variable :c:data:`errno`. The most general function " "is :c:func:`PyErr_SetObject`, which takes two object arguments, the " "exception and its associated value. You don't need to :c:func:`Py_INCREF` " "the objects passed to any of these functions." msgstr "" #: ../../extending/extending.rst:45 msgid "" "You can test non-destructively whether an exception has been set " "with :c:func:`PyErr_Occurred`. This returns the current exception object, " "or ``NULL`` if no exception has occurred. You normally don't need to " "call :c:func:`PyErr_Occurred` to see whether an error occurred in a function " "call, since you should be able to tell from the return value." msgstr "" #: ../../extending/extending.rst:51 msgid "" "When a function *f* that calls another function *g* detects that the latter " "fails, *f* should itself return an error value (usually ``NULL`` or " "``-1``). It should *not* call one of the ``PyErr_*`` functions --- one has " "already been called by *g*. *f*'s caller is then supposed to also return an " "error indication to *its* caller, again *without* calling ``PyErr_*``, and " "so on --- the most detailed cause of the error was already reported by the " "function that first detected it. Once the error reaches the Python " "interpreter's main loop, this aborts the currently executing Python code and " "tries to find an exception handler specified by the Python programmer." msgstr "" #: ../../extending/extending.rst:61 msgid "" "(There are situations where a module can actually give a more detailed error " "message by calling another ``PyErr_*`` function, and in such cases it is " "fine to do so. As a general rule, however, this is not necessary, and can " "cause information about the cause of the error to be lost: most operations " "can fail for a variety of reasons.)" msgstr "" #: ../../extending/extending.rst:67 msgid "" "To ignore an exception set by a function call that failed, the exception " "condition must be cleared explicitly by calling :c:func:`PyErr_Clear`. The " "only time C code should call :c:func:`PyErr_Clear` is if it doesn't want to " "pass the error on to the interpreter but wants to handle it completely by " "itself (possibly by trying something else, or pretending nothing went wrong)." msgstr "" #: ../../extending/extending.rst:73 msgid "" "Every failing :c:func:`malloc` call must be turned into an exception --- the " "direct caller of :c:func:`malloc` (or :c:func:`realloc`) must " "call :c:func:`PyErr_NoMemory` and return a failure indicator itself. All " "the object-creating functions (for example, :c:func:`PyLong_FromLong`) " "already do this, so this note is only relevant to those who " "call :c:func:`malloc` directly." msgstr "" #: ../../extending/extending.rst:79 msgid "" "Also note that, with the important exception of :c:func:`PyArg_ParseTuple` " "and friends, functions that return an integer status usually return a " "positive value or zero for success and ``-1`` for failure, like Unix system " "calls." msgstr "" #: ../../extending/extending.rst:83 msgid "" "Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` " "or :c:func:`Py_DECREF` calls for objects you have already created) when you " "return an error indicator!" msgstr "" #: ../../extending/extending.rst:87 msgid "" "The choice of which exception to raise is entirely yours. There are " "predeclared C objects corresponding to all built-in Python exceptions, such " "as :c:data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, " "you should choose exceptions wisely --- don't use :c:data:`PyExc_TypeError` " "to mean that a file couldn't be opened (that should probably " "be :c:data:`PyExc_OSError`). If something's wrong with the argument list, " "the :c:func:`PyArg_ParseTuple` function usually " "raises :c:data:`PyExc_TypeError`. If you have an argument whose value must " "be in a particular range or must satisfy other " "conditions, :c:data:`PyExc_ValueError` is appropriate." msgstr "" #: ../../extending/extending.rst:97 msgid "" "You can also define a new exception that is unique to your module. The " "simplest way to do this is to declare a static global object variable at the " "beginning of the file::" msgstr "" #: ../../extending/extending.rst:101 msgid "static PyObject *SpamError = NULL;" msgstr "" #: ../../extending/extending.rst:103 msgid "" "and initialize it by calling :c:func:`PyErr_NewException` in the " "module's :c:data:`Py_mod_exec` function (:c:func:`!spam_module_exec`)::" msgstr "" #: ../../extending/extending.rst:106 msgid "SpamError = PyErr_NewException(\"spam.error\", NULL, NULL);" msgstr "" #: ../../extending/extending.rst:108 msgid "" "Since :c:data:`!SpamError` is a global variable, it will be overwritten " "every time the module is reinitialized, when the :c:data:`Py_mod_exec` " "function is called." msgstr "" #: ../../extending/extending.rst:111 msgid "" "For now, let's avoid the issue: we will block repeated initialization by " "raising an :py:exc:`ImportError`::" msgstr "" #: ../../extending/extending.rst:114 msgid "" "static PyObject *SpamError = NULL;\n" "\n" "static int\n" "spam_module_exec(PyObject *m)\n" "{\n" " if (SpamError != NULL) {\n" " PyErr_SetString(PyExc_ImportError,\n" " \"cannot initialize spam module more than once\");\n" " return -1;\n" " }\n" " SpamError = PyErr_NewException(\"spam.error\", NULL, NULL);\n" " if (PyModule_AddObjectRef(m, \"SpamError\", SpamError) < 0) {\n" " return -1;\n" " }\n" "\n" " return 0;\n" "}\n" "\n" "static PyModuleDef_Slot spam_module_slots[] = {\n" " {Py_mod_exec, spam_module_exec},\n" " {0, NULL}\n" "};\n" "\n" "static struct PyModuleDef spam_module = {\n" " .m_base = PyModuleDef_HEAD_INIT,\n" " .m_name = \"spam\",\n" " .m_size = 0, // non-negative\n" " .m_slots = spam_module_slots,\n" "};\n" "\n" "PyMODINIT_FUNC\n" "PyInit_spam(void)\n" "{\n" " return PyModuleDef_Init(&spam_module);\n" "}" msgstr "" #: ../../extending/extending.rst:150 msgid "" "Note that the Python name for the exception object is :exc:`!spam.error`. " "The :c:func:`PyErr_NewException` function may create a class with the base " "class being :exc:`Exception` (unless another class is passed in instead of " "``NULL``), described in :ref:`bltin-exceptions`." msgstr "" #: ../../extending/extending.rst:155 msgid "" "Note also that the :c:data:`!SpamError` variable retains a reference to the " "newly created exception class; this is intentional! Since the exception " "could be removed from the module by external code, an owned reference to the " "class is needed to ensure that it will not be discarded, causing :c:data:`!" "SpamError` to become a dangling pointer. Should it become a dangling " "pointer, C code which raises the exception could cause a core dump or other " "unintended side effects." msgstr "" #: ../../extending/extending.rst:162 msgid "" "For now, the :c:func:`Py_DECREF` call to remove this reference is missing. " "Even when the Python interpreter shuts down, the global :c:data:`!SpamError` " "variable will not be garbage-collected. It will \"leak\". We did, however, " "ensure that this will happen at most once per process." msgstr "" #: ../../extending/extending.rst:167 msgid "" "We discuss the use of :c:macro:`PyMODINIT_FUNC` as a function return type " "later in this sample." msgstr "" #: ../../extending/extending.rst:170 msgid "" "The :exc:`!spam.error` exception can be raised in your extension module " "using a call to :c:func:`PyErr_SetString` as shown below::" msgstr "" #: ../../extending/extending.rst:173 msgid "" "static PyObject *\n" "spam_system(PyObject *self, PyObject *args)\n" "{\n" " const char *command;\n" " int sts;\n" "\n" " if (!PyArg_ParseTuple(args, \"s\", &command))\n" " return NULL;\n" " sts = system(command);\n" " if (sts < 0) {\n" " PyErr_SetString(SpamError, \"System command failed\");\n" " return NULL;\n" " }\n" " return PyLong_FromLong(sts);\n" "}" msgstr "" #: ../../extending/extending.rst:193 msgid "Embedding an extension" msgstr "" #: ../../extending/extending.rst:195 msgid "" "If you want to make your module a permanent part of the Python interpreter, " "you will have to change the configuration setup and rebuild the " "interpreter. On Unix, place your file (:file:`spammodule.c` for example) in " "the :file:`Modules/` directory of an unpacked source distribution, add a " "line to the file :file:`Modules/Setup.local` describing your file:" msgstr "" #: ../../extending/extending.rst:202 msgid "spam spammodule.o" msgstr "" #: ../../extending/extending.rst:206 msgid "" "and rebuild the interpreter by running :program:`make` in the toplevel " "directory. You can also run :program:`make` in the :file:`Modules/` " "subdirectory, but then you must first rebuild :file:`Makefile` there by " "running ':program:`make` Makefile'. (This is necessary each time you change " "the :file:`Setup` file.)" msgstr "" #: ../../extending/extending.rst:212 msgid "" "If your module requires additional libraries to link with, these can be " "listed on the line in the configuration file as well, for instance:" msgstr "" #: ../../extending/extending.rst:215 msgid "spam spammodule.o -lX11" msgstr "" #: ../../extending/extending.rst:223 msgid "Calling Python Functions from C" msgstr "" #: ../../extending/extending.rst:225 msgid "" "The tutorial concentrated on making C functions callable from Python. The " "reverse is also useful: calling Python functions from C. This is especially " "the case for libraries that support so-called \"callback\" functions. If a " "C interface makes use of callbacks, the equivalent Python often needs to " "provide a callback mechanism to the Python programmer; the implementation " "will require calling the Python callback functions from a C callback. Other " "uses are also imaginable." msgstr "" #: ../../extending/extending.rst:233 msgid "" "Fortunately, the Python interpreter is easily called recursively, and there " "is a standard interface to call a Python function. (If you're interested in " "how to call the Python parser with a particular string as input, " "see :ref:`veryhigh`.)" msgstr "" #: ../../extending/extending.rst:237 msgid "" "Calling a Python function is easy. First, the Python program must somehow " "pass you the Python function object. You should provide a function (or some " "other interface) to do this. When this function is called, save a pointer " "to the Python function object (be careful to :c:func:`Py_INCREF` it!) in a " "global variable --- or wherever you see fit. For example, the following " "function might be part of a module definition::" msgstr "" #: ../../extending/extending.rst:244 msgid "" "static PyObject *my_callback = NULL;\n" "\n" "static PyObject *\n" "my_set_callback(PyObject *dummy, PyObject *args)\n" "{\n" " PyObject *result = NULL;\n" " PyObject *temp;\n" "\n" " if (PyArg_ParseTuple(args, \"O:set_callback\", &temp)) {\n" " if (!PyCallable_Check(temp)) {\n" " PyErr_SetString(PyExc_TypeError, \"parameter must be " "callable\");\n" " return NULL;\n" " }\n" " Py_XINCREF(temp); /* Add a reference to new callback */\n" " Py_XDECREF(my_callback); /* Dispose of previous callback */\n" " my_callback = temp; /* Remember new callback */\n" " /* Boilerplate to return \"None\" */\n" " Py_INCREF(Py_None);\n" " result = Py_None;\n" " }\n" " return result;\n" "}" msgstr "" #: ../../extending/extending.rst:267 msgid "" "This function must be registered with the interpreter using " "the :c:macro:`METH_VARARGS` flag in :c:type:`PyMethodDef.ml_flags`. " "The :c:func:`PyArg_ParseTuple` function and its arguments are documented in " "section :ref:`parsetuple`." msgstr "" #: ../../extending/extending.rst:272 msgid "" "The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement " "the reference count of an object and are safe in the presence of ``NULL`` " "pointers (but note that *temp* will not be ``NULL`` in this context). More " "info on them in section :ref:`refcounts`." msgstr "" #: ../../extending/extending.rst:279 msgid "" "Later, when it is time to call the function, you call the C " "function :c:func:`PyObject_CallObject`. This function has two arguments, " "both pointers to arbitrary Python objects: the Python function, and the " "argument list. The argument list must always be a tuple object, whose " "length is the number of arguments. To call the Python function with no " "arguments, pass in ``NULL``, or an empty tuple; to call it with one " "argument, pass a singleton tuple. :c:func:`Py_BuildValue` returns a tuple " "when its format string consists of zero or more format codes between " "parentheses. For example::" msgstr "" #: ../../extending/extending.rst:288 msgid "" "int arg;\n" "PyObject *arglist;\n" "PyObject *result;\n" "...\n" "arg = 123;\n" "...\n" "/* Time to call the callback */\n" "arglist = Py_BuildValue(\"(i)\", arg);\n" "result = PyObject_CallObject(my_callback, arglist);\n" "Py_DECREF(arglist);" msgstr "" #: ../../extending/extending.rst:299 msgid "" ":c:func:`PyObject_CallObject` returns a Python object pointer: this is the " "return value of the Python function. :c:func:`PyObject_CallObject` is " "\"reference-count-neutral\" with respect to its arguments. In the example a " "new tuple was created to serve as the argument list, which " "is :c:func:`Py_DECREF`\\ -ed immediately after " "the :c:func:`PyObject_CallObject` call." msgstr "" #: ../../extending/extending.rst:306 msgid "" "The return value of :c:func:`PyObject_CallObject` is \"new\": either it is a " "brand new object, or it is an existing object whose reference count has been " "incremented. So, unless you want to save it in a global variable, you " "should somehow :c:func:`Py_DECREF` the result, even (especially!) if you are " "not interested in its value." msgstr "" #: ../../extending/extending.rst:312 msgid "" "Before you do this, however, it is important to check that the return value " "isn't ``NULL``. If it is, the Python function terminated by raising an " "exception. If the C code that called :c:func:`PyObject_CallObject` is called " "from Python, it should now return an error indication to its Python caller, " "so the interpreter can print a stack trace, or the calling Python code can " "handle the exception. If this is not possible or desirable, the exception " "should be cleared by calling :c:func:`PyErr_Clear`. For example::" msgstr "" #: ../../extending/extending.rst:320 msgid "" "if (result == NULL)\n" " return NULL; /* Pass error back */\n" "...use result...\n" "Py_DECREF(result);" msgstr "" #: ../../extending/extending.rst:325 msgid "" "Depending on the desired interface to the Python callback function, you may " "also have to provide an argument list to :c:func:`PyObject_CallObject`. In " "some cases the argument list is also provided by the Python program, through " "the same interface that specified the callback function. It can then be " "saved and used in the same manner as the function object. In other cases, " "you may have to construct a new tuple to pass as the argument list. The " "simplest way to do this is to call :c:func:`Py_BuildValue`. For example, if " "you want to pass an integral event code, you might use the following code::" msgstr "" #: ../../extending/extending.rst:334 msgid "" "PyObject *arglist;\n" "...\n" "arglist = Py_BuildValue(\"(l)\", eventcode);\n" "if (arglist == NULL)\n" " return NULL;\n" "result = PyObject_CallObject(my_callback, arglist);\n" "Py_DECREF(arglist);\n" "if (result == NULL)\n" " return NULL; /* Pass error back */\n" "/* Here maybe use the result */\n" "Py_DECREF(result);" msgstr "" #: ../../extending/extending.rst:346 msgid "" "Note the placement of ``Py_DECREF(arglist)`` immediately after the call, " "before the error check!" msgstr "" #: ../../extending/extending.rst:349 msgid "" "You may also call a function with keyword arguments by " "using :c:func:`PyObject_Call`, which supports arguments and keyword " "arguments. As in the above example, we use :c:func:`Py_BuildValue` to " "construct the dictionary. ::" msgstr "" #: ../../extending/extending.rst:353 msgid "" "PyObject *arglist, *dict;\n" "...\n" "arglist = PyTuple_New(0);\n" "if (arglist == NULL)\n" " return NULL;\n" "dict = Py_BuildValue(\"{s:i}\", \"name\", val);\n" "if (dict == NULL) {\n" " Py_DECREF(arglist);\n" " return NULL;\n" "}\n" "result = PyObject_Call(my_callback, arglist, dict);\n" "Py_DECREF(arglist);\n" "Py_DECREF(dict);\n" "if (result == NULL)\n" " return NULL; /* Pass error back */\n" "/* Here maybe use the result */\n" "Py_DECREF(result);" msgstr "" #: ../../extending/extending.rst:377 msgid "Extracting Parameters in Extension Functions" msgstr "" #: ../../extending/extending.rst:379 msgid "" "The :ref:`tutorial ` uses a \":c:data:`METH_O`\" " "function, which is limited to a single Python argument. If you want more, " "you can use :c:data:`METH_VARARGS` instead. With this flag, the C function " "will receive a :py:class:`tuple` of arguments instead of a single object." msgstr "" #: ../../extending/extending.rst:385 msgid "" "For unpacking the tuple, CPython provides the :c:func:`PyArg_ParseTuple` " "function, declared as follows::" msgstr "" #: ../../extending/extending.rst:388 msgid "int PyArg_ParseTuple(PyObject *arg, const char *format, ...);" msgstr "" #: ../../extending/extending.rst:390 msgid "" "The *arg* argument must be a tuple object containing an argument list passed " "from Python to a C function. The *format* argument must be a format string, " "whose syntax is explained in :ref:`arg-parsing` in the Python/C API " "Reference Manual. The remaining arguments must be addresses of variables " "whose type is determined by the format string." msgstr "" #: ../../extending/extending.rst:396 msgid "" "For example, to receive a single Python :py:class:`str` object and turn it " "into a C buffer, you would use ``\"s\"`` as the format string::" msgstr "" #: ../../extending/extending.rst:399 msgid "" "const char *command;\n" "if (!PyArg_ParseTuple(args, \"s\", &command)) {\n" " return NULL;\n" "}" msgstr "" #: ../../extending/extending.rst:404 msgid "" "If an error is detected in the argument list, :c:func:`!PyArg_ParseTuple` " "returns ``NULL`` (the error indicator for functions returning object " "pointers); your function may return ``NULL``, relying on the exception set " "by :c:func:`PyArg_ParseTuple`." msgstr "" #: ../../extending/extending.rst:409 msgid "" "Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments " "have the required types, it cannot check the validity of the addresses of C " "variables passed to the call: if you make mistakes there, your code will " "probably crash or at least overwrite random bits in memory. So be careful!" msgstr "" #: ../../extending/extending.rst:414 msgid "" "Note that any Python object references which are provided to the caller are " "*borrowed* references; do not decrement their reference count!" msgstr "" #: ../../extending/extending.rst:417 msgid "Some example calls::" msgstr "" #: ../../extending/extending.rst:419 ../../extending/extending.rst:1012 msgid "#include " msgstr "" #: ../../extending/extending.rst:423 msgid "" "int ok;\n" "int i, j;\n" "long k, l;\n" "const char *s;\n" "Py_ssize_t size;\n" "\n" "ok = PyArg_ParseTuple(args, \"\"); /* No arguments */\n" " /* Python call: f() */" msgstr "" #: ../../extending/extending.rst:434 msgid "" "ok = PyArg_ParseTuple(args, \"s\", &s); /* A string */\n" " /* Possible Python call: f('whoops!') */" msgstr "" #: ../../extending/extending.rst:439 msgid "" "ok = PyArg_ParseTuple(args, \"lls\", &k, &l, &s); /* Two longs and a string " "*/\n" " /* Possible Python call: f(1, 2, 'three') */" msgstr "" #: ../../extending/extending.rst:444 msgid "" "ok = PyArg_ParseTuple(args, \"(ii)s#\", &i, &j, &s, &size);\n" " /* A pair of ints and a string, whose size is also returned */\n" " /* Possible Python call: f((1, 2), 'three') */" msgstr "" #: ../../extending/extending.rst:450 msgid "" "{\n" " const char *file;\n" " const char *mode = \"r\";\n" " int bufsize = 0;\n" " ok = PyArg_ParseTuple(args, \"s|si\", &file, &mode, &bufsize);\n" " /* A string, and optionally another string and an integer */\n" " /* Possible Python calls:\n" " f('spam')\n" " f('spam', 'w')\n" " f('spam', 'wb', 100000) */\n" "}" msgstr "" #: ../../extending/extending.rst:464 msgid "" "{\n" " int left, top, right, bottom, h, v;\n" " ok = PyArg_ParseTuple(args, \"((ii)(ii))(ii)\",\n" " &left, &top, &right, &bottom, &h, &v);\n" " /* A rectangle and a point */\n" " /* Possible Python call:\n" " f(((0, 0), (400, 300)), (10, 10)) */\n" "}" msgstr "" #: ../../extending/extending.rst:475 msgid "" "{\n" " Py_complex c;\n" " ok = PyArg_ParseTuple(args, \"D:myfunction\", &c);\n" " /* a complex, also providing a function name for errors */\n" " /* Possible Python call: myfunction(1+2j) */\n" "}" msgstr "" #: ../../extending/extending.rst:486 msgid "Keyword Parameters for Extension Functions" msgstr "" #: ../../extending/extending.rst:488 msgid "" "If you also want your function to accept :term:`keyword arguments `, use the :c:data:`METH_KEYWORDS` flag in combination " "with :c:data:`METH_VARARGS`. (:c:data:`!METH_KEYWORDS` can also be used with " "other flags; see its documentation for the allowed combinations.)" msgstr "" #: ../../extending/extending.rst:494 msgid "" "In this case, the C function should accept a third ``PyObject *`` parameter " "which will be a dictionary of keywords. " "Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a " "function." msgstr "" #: ../../extending/extending.rst:501 msgid "" "The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::" msgstr "" #: ../../extending/extending.rst:503 msgid "" "int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,\n" " const char *format, char * const " "*kwlist, ...);" msgstr "" #: ../../extending/extending.rst:506 msgid "" "The *arg* and *format* parameters are identical to those of " "the :c:func:`PyArg_ParseTuple` function. The *kwdict* parameter is the " "dictionary of keywords received as the third parameter from the Python " "runtime. The *kwlist* parameter is a ``NULL``-terminated list of strings " "which identify the parameters; the names are matched with the type " "information from *format* from left to right. On " "success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise it " "returns false and raises an appropriate exception." msgstr "" #: ../../extending/extending.rst:516 msgid "" "Nested tuples cannot be parsed when using keyword arguments! Keyword " "parameters passed in which are not present in the *kwlist* will " "cause :exc:`TypeError` to be raised." msgstr "" #: ../../extending/extending.rst:522 msgid "" "Here is an example module which uses keywords, based on an example by Geoff " "Philbrick (philbrick@hks.com)::" msgstr "" #: ../../extending/extending.rst:525 msgid "" "#define PY_SSIZE_T_CLEAN\n" "#include \n" "\n" "static PyObject *\n" "keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)\n" "{\n" " int voltage;\n" " const char *state = \"a stiff\";\n" " const char *action = \"voom\";\n" " const char *type = \"Norwegian Blue\";\n" "\n" " static char *kwlist[] = {\"voltage\", \"state\", \"action\", \"type\", " "NULL};\n" "\n" " if (!PyArg_ParseTupleAndKeywords(args, keywds, \"i|sss\", kwlist,\n" " &voltage, &state, &action, &type))\n" " return NULL;\n" "\n" " printf(\"-- This parrot wouldn't %s if you put %i Volts through it." "\\n\",\n" " action, voltage);\n" " printf(\"-- Lovely plumage, the %s -- It's %s!\\n\", type, state);\n" "\n" " Py_RETURN_NONE;\n" "}\n" "\n" "static PyMethodDef keywdarg_methods[] = {\n" " /* The cast of the function is necessary since PyCFunction values\n" " * only take two PyObject* parameters, and keywdarg_parrot() takes\n" " * three.\n" " */\n" " {\"parrot\", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | " "METH_KEYWORDS,\n" " \"Print a lovely skit to standard output.\"},\n" " {NULL, NULL, 0, NULL} /* sentinel */\n" "};" msgstr "" #: ../../extending/extending.rst:563 msgid "Building Arbitrary Values" msgstr "" #: ../../extending/extending.rst:565 msgid "" "This function is the counterpart to :c:func:`PyArg_ParseTuple`. It is " "declared as follows::" msgstr "" #: ../../extending/extending.rst:568 msgid "PyObject *Py_BuildValue(const char *format, ...);" msgstr "" #: ../../extending/extending.rst:570 msgid "" "It recognizes a set of format units similar to the ones recognized " "by :c:func:`PyArg_ParseTuple`, but the arguments (which are input to the " "function, not output) must not be pointers, just values. It returns a new " "Python object, suitable for returning from a C function called from Python." msgstr "" #: ../../extending/extending.rst:575 msgid "" "One difference with :c:func:`PyArg_ParseTuple`: while the latter requires " "its first argument to be a tuple (since Python argument lists are always " "represented as tuples internally), :c:func:`Py_BuildValue` does not always " "build a tuple. It builds a tuple only if its format string contains two or " "more format units. If the format string is empty, it returns ``None``; if it " "contains exactly one format unit, it returns whatever object is described by " "that format unit. To force it to return a tuple of size 0 or one, " "parenthesize the format string." msgstr "" #: ../../extending/extending.rst:583 msgid "" "Examples (to the left the call, to the right the resulting Python value):" msgstr "" #: ../../extending/extending.rst:585 msgid "" "Py_BuildValue(\"\") None\n" "Py_BuildValue(\"i\", 123) 123\n" "Py_BuildValue(\"iii\", 123, 456, 789) (123, 456, 789)\n" "Py_BuildValue(\"s\", \"hello\") 'hello'\n" "Py_BuildValue(\"y\", \"hello\") b'hello'\n" "Py_BuildValue(\"ss\", \"hello\", \"world\") ('hello', 'world')\n" "Py_BuildValue(\"s#\", \"hello\", 4) 'hell'\n" "Py_BuildValue(\"y#\", \"hello\", 4) b'hell'\n" "Py_BuildValue(\"()\") ()\n" "Py_BuildValue(\"(i)\", 123) (123,)\n" "Py_BuildValue(\"(ii)\", 123, 456) (123, 456)\n" "Py_BuildValue(\"(i,i)\", 123, 456) (123, 456)\n" "Py_BuildValue(\"[i,i]\", 123, 456) [123, 456]\n" "Py_BuildValue(\"{s:i,s:i}\",\n" " \"abc\", 123, \"def\", 456) {'abc': 123, 'def': 456}\n" "Py_BuildValue(\"((ii)(ii)) (ii)\",\n" " 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))" msgstr "" #: ../../extending/extending.rst:609 msgid "Reference Counts" msgstr "" #: ../../extending/extending.rst:611 msgid "" "In languages like C or C++, the programmer is responsible for dynamic " "allocation and deallocation of memory on the heap. In C, this is done using " "the functions :c:func:`malloc` and :c:func:`free`. In C++, the operators " "``new`` and ``delete`` are used with essentially the same meaning and we'll " "restrict the following discussion to the C case." msgstr "" #: ../../extending/extending.rst:617 msgid "" "Every block of memory allocated with :c:func:`malloc` should eventually be " "returned to the pool of available memory by exactly one call " "to :c:func:`free`. It is important to call :c:func:`free` at the right " "time. If a block's address is forgotten but :c:func:`free` is not called " "for it, the memory it occupies cannot be reused until the program " "terminates. This is called a :dfn:`memory leak`. On the other hand, if a " "program calls :c:func:`free` for a block and then continues to use the " "block, it creates a conflict with reuse of the block through " "another :c:func:`malloc` call. This is called :dfn:`using freed memory`. It " "has the same bad consequences as referencing uninitialized data --- core " "dumps, wrong results, mysterious crashes." msgstr "" #: ../../extending/extending.rst:628 msgid "" "Common causes of memory leaks are unusual paths through the code. For " "instance, a function may allocate a block of memory, do some calculation, " "and then free the block again. Now a change in the requirements for the " "function may add a test to the calculation that detects an error condition " "and can return prematurely from the function. It's easy to forget to free " "the allocated memory block when taking this premature exit, especially when " "it is added later to the code. Such leaks, once introduced, often go " "undetected for a long time: the error exit is taken only in a small fraction " "of all calls, and most modern machines have plenty of virtual memory, so the " "leak only becomes apparent in a long-running process that uses the leaking " "function frequently. Therefore, it's important to prevent leaks from " "happening by having a coding convention or strategy that minimizes this kind " "of errors." msgstr "" #: ../../extending/extending.rst:641 msgid "" "Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it " "needs a strategy to avoid memory leaks as well as the use of freed memory. " "The chosen method is called :dfn:`reference counting`. The principle is " "simple: every object contains a counter, which is incremented when a " "reference to the object is stored somewhere, and which is decremented when a " "reference to it is deleted. When the counter reaches zero, the last " "reference to the object has been deleted and the object is freed." msgstr "" #: ../../extending/extending.rst:649 msgid "" "An alternative strategy is called :dfn:`automatic garbage collection`. " "(Sometimes, reference counting is also referred to as a garbage collection " "strategy, hence the use of \"automatic\" to distinguish the two.) The big " "advantage of automatic garbage collection is that the user doesn't need to " "call :c:func:`free` explicitly. (Another claimed advantage is an " "improvement in speed or memory usage --- this is no hard fact however.) The " "disadvantage is that for C, there is no truly portable automatic garbage " "collector, while reference counting can be implemented portably (as long as " "the functions :c:func:`malloc` and :c:func:`free` are available --- which " "the C Standard guarantees). Maybe some day a sufficiently portable automatic " "garbage collector will be available for C. Until then, we'll have to live " "with reference counts." msgstr "" #: ../../extending/extending.rst:661 msgid "" "While Python uses the traditional reference counting implementation, it also " "offers a cycle detector that works to detect reference cycles. This allows " "applications to not worry about creating direct or indirect circular " "references; these are the weakness of garbage collection implemented using " "only reference counting. Reference cycles consist of objects which contain " "(possibly indirect) references to themselves, so that each object in the " "cycle has a reference count which is non-zero. Typical reference counting " "implementations are not able to reclaim the memory belonging to any objects " "in a reference cycle, or referenced from the objects in the cycle, even " "though there are no further references to the cycle itself." msgstr "" #: ../../extending/extending.rst:672 msgid "" "The cycle detector is able to detect garbage cycles and can reclaim them. " "The :mod:`gc` module exposes a way to run the detector " "(the :func:`~gc.collect` function), as well as configuration interfaces and " "the ability to disable the detector at runtime." msgstr "" #: ../../extending/extending.rst:681 msgid "Reference Counting in Python" msgstr "" #: ../../extending/extending.rst:683 msgid "" "There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle " "the incrementing and decrementing of the reference " "count. :c:func:`Py_DECREF` also frees the object when the count reaches " "zero. For flexibility, it doesn't call :c:func:`free` directly --- rather, " "it makes a call through a function pointer in the object's :dfn:`type " "object`. For this purpose (and others), every object also contains a " "pointer to its type object." msgstr "" #: ../../extending/extending.rst:690 msgid "" "The big question now remains: when to use ``Py_INCREF(x)`` and " "``Py_DECREF(x)``? Let's first introduce some terms. Nobody \"owns\" an " "object; however, you can :dfn:`own a reference` to an object. An object's " "reference count is now defined as the number of owned references to it. The " "owner of a reference is responsible for calling :c:func:`Py_DECREF` when the " "reference is no longer needed. Ownership of a reference can be " "transferred. There are three ways to dispose of an owned reference: pass it " "on, store it, or call :c:func:`Py_DECREF`. Forgetting to dispose of an owned " "reference creates a memory leak." msgstr "" #: ../../extending/extending.rst:699 msgid "" "It is also possible to :dfn:`borrow` [#borrow]_ a reference to an object. " "The borrower of a reference should not call :c:func:`Py_DECREF`. The " "borrower must not hold on to the object longer than the owner from which it " "was borrowed. Using a borrowed reference after the owner has disposed of it " "risks using freed memory and should be avoided completely [#dont-check-" "refcount]_." msgstr "" #: ../../extending/extending.rst:705 msgid "" "The advantage of borrowing over owning a reference is that you don't need to " "take care of disposing of the reference on all possible paths through the " "code --- in other words, with a borrowed reference you don't run the risk of " "leaking when a premature exit is taken. The disadvantage of borrowing over " "owning is that there are some subtle situations where in seemingly correct " "code a borrowed reference can be used after the owner from which it was " "borrowed has in fact disposed of it." msgstr "" #: ../../extending/extending.rst:713 msgid "" "A borrowed reference can be changed into an owned reference by " "calling :c:func:`Py_INCREF`. This does not affect the status of the owner " "from which the reference was borrowed --- it creates a new owned reference, " "and gives full owner responsibilities (the new owner must dispose of the " "reference properly, as well as the previous owner)." msgstr "" #: ../../extending/extending.rst:723 msgid "Ownership Rules" msgstr "" #: ../../extending/extending.rst:725 msgid "" "Whenever an object reference is passed into or out of a function, it is part " "of the function's interface specification whether ownership is transferred " "with the reference or not." msgstr "" #: ../../extending/extending.rst:729 msgid "" "Most functions that return a reference to an object pass on ownership with " "the reference. In particular, all functions whose function it is to create " "a new object, such as :c:func:`PyLong_FromLong` and :c:func:`Py_BuildValue`, " "pass ownership to the receiver. Even if the object is not actually new, you " "still receive ownership of a new reference to that object. For " "instance, :c:func:`PyLong_FromLong` maintains a cache of popular values and " "can return a reference to a cached item." msgstr "" #: ../../extending/extending.rst:737 msgid "" "Many functions that extract objects from other objects also transfer " "ownership with the reference, for " "instance :c:func:`PyObject_GetAttrString`. The picture is less clear, here, " "however, since a few common routines are " "exceptions: :c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, " "and :c:func:`PyDict_GetItemString` all return references that you borrow " "from the tuple, list or dictionary." msgstr "" #: ../../extending/extending.rst:744 msgid "" "The function :c:func:`PyImport_AddModule` also returns a borrowed reference, " "even though it may actually create the object it returns: this is possible " "because an owned reference to the object is stored in ``sys.modules``." msgstr "" #: ../../extending/extending.rst:748 msgid "" "When you pass an object reference into another function, in general, the " "function borrows the reference from you --- if it needs to store it, it will " "use :c:func:`Py_INCREF` to become an independent owner. There are exactly " "two important exceptions to this rule: :c:func:`PyTuple_SetItem` " "and :c:func:`PyList_SetItem`. These functions take over ownership of the " "item passed to them --- even if they fail! (Note " "that :c:func:`PyDict_SetItem` and friends don't take over ownership --- they " "are \"normal.\")" msgstr "" #: ../../extending/extending.rst:756 msgid "" "When a C function is called from Python, it borrows references to its " "arguments from the caller. The caller owns a reference to the object, so " "the borrowed reference's lifetime is guaranteed until the function returns. " "Only when such a borrowed reference must be stored or passed on, it must be " "turned into an owned reference by calling :c:func:`Py_INCREF`." msgstr "" #: ../../extending/extending.rst:762 msgid "" "The object reference returned from a C function that is called from Python " "must be an owned reference --- ownership is transferred from the function to " "its caller." msgstr "" #: ../../extending/extending.rst:770 msgid "Thin Ice" msgstr "" #: ../../extending/extending.rst:772 msgid "" "There are a few situations where seemingly harmless use of a borrowed " "reference can lead to problems. These all have to do with implicit " "invocations of the interpreter, which can cause the owner of a reference to " "dispose of it." msgstr "" #: ../../extending/extending.rst:776 msgid "" "The first and most important case to know about is using :c:func:`Py_DECREF` " "on an unrelated object while borrowing a reference to a list item. For " "instance::" msgstr "" #: ../../extending/extending.rst:779 msgid "" "void\n" "bug(PyObject *list)\n" "{\n" " PyObject *item = PyList_GetItem(list, 0);\n" "\n" " PyList_SetItem(list, 1, PyLong_FromLong(0L));\n" " PyObject_Print(item, stdout, 0); /* BUG! */\n" "}" msgstr "" #: ../../extending/extending.rst:788 msgid "" "This function first borrows a reference to ``list[0]``, then replaces " "``list[1]`` with the value ``0``, and finally prints the borrowed reference. " "Looks harmless, right? But it's not!" msgstr "" #: ../../extending/extending.rst:792 msgid "" "Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns " "references to all its items, so when item 1 is replaced, it has to dispose " "of the original item 1. Now let's suppose the original item 1 was an " "instance of a user-defined class, and let's further suppose that the class " "defined a :meth:`!__del__` method. If this class instance has a reference " "count of 1, disposing of it will call its :meth:`!__del__` method. " "Internally, :c:func:`PyList_SetItem` calls :c:func:`Py_DECREF` on the " "replaced item, which invokes replaced item's " "corresponding :c:member:`~PyTypeObject.tp_dealloc` function. During " "deallocation, :c:member:`~PyTypeObject.tp_dealloc` " "calls :c:member:`~PyTypeObject.tp_finalize`, which is mapped to the :meth:`!" "__del__` method for class instances (see :pep:`442`). This entire sequence " "happens synchronously within the :c:func:`PyList_SetItem` call." msgstr "" #: ../../extending/extending.rst:806 msgid "" "Since it is written in Python, the :meth:`!__del__` method can execute " "arbitrary Python code. Could it perhaps do something to invalidate the " "reference to ``item`` in :c:func:`!bug`? You bet! Assuming that the list " "passed into :c:func:`!bug` is accessible to the :meth:`!__del__` method, it " "could execute a statement to the effect of ``del list[0]``, and assuming " "this was the last reference to that object, it would free the memory " "associated with it, thereby invalidating ``item``." msgstr "" #: ../../extending/extending.rst:814 msgid "" "The solution, once you know the source of the problem, is easy: temporarily " "increment the reference count. The correct version of the function reads::" msgstr "" #: ../../extending/extending.rst:817 msgid "" "void\n" "no_bug(PyObject *list)\n" "{\n" " PyObject *item = PyList_GetItem(list, 0);\n" "\n" " Py_INCREF(item);\n" " PyList_SetItem(list, 1, PyLong_FromLong(0L));\n" " PyObject_Print(item, stdout, 0);\n" " Py_DECREF(item);\n" "}" msgstr "" #: ../../extending/extending.rst:828 msgid "" "This is a true story. An older version of Python contained variants of this " "bug and someone spent a considerable amount of time in a C debugger to " "figure out why his :meth:`!__del__` methods would fail..." msgstr "" #: ../../extending/extending.rst:832 msgid "" "The second case of problems with a borrowed reference is a variant involving " "threads. Normally, multiple threads in the Python interpreter can't get in " "each other's way, because there is a :term:`global lock ` protecting Python's entire object space. However, it is possible to " "temporarily release this lock using the " "macro :c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it " "using :c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O " "calls, to let other threads use the processor while waiting for the I/O to " "complete. Obviously, the following function has the same problem as the " "previous one::" msgstr "" #: ../../extending/extending.rst:842 msgid "" "void\n" "bug(PyObject *list)\n" "{\n" " PyObject *item = PyList_GetItem(list, 0);\n" " Py_BEGIN_ALLOW_THREADS\n" " ...some blocking I/O call...\n" " Py_END_ALLOW_THREADS\n" " PyObject_Print(item, stdout, 0); /* BUG! */\n" "}" msgstr "" #: ../../extending/extending.rst:856 msgid "NULL Pointers" msgstr "" #: ../../extending/extending.rst:858 msgid "" "In general, functions that take object references as arguments do not expect " "you to pass them ``NULL`` pointers, and will dump core (or cause later core " "dumps) if you do so. Functions that return object references generally " "return ``NULL`` only to indicate that an exception occurred. The reason for " "not testing for ``NULL`` arguments is that functions often pass the objects " "they receive on to other function --- if each function were to test for " "``NULL``, there would be a lot of redundant tests and the code would run " "more slowly." msgstr "" #: ../../extending/extending.rst:866 msgid "" "It is better to test for ``NULL`` only at the \"source:\" when a pointer " "that may be ``NULL`` is received, for example, from :c:func:`malloc` or from " "a function that may raise an exception." msgstr "" #: ../../extending/extending.rst:870 msgid "" "The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for " "``NULL`` pointers --- however, their variants :c:func:`Py_XINCREF` " "and :c:func:`Py_XDECREF` do." msgstr "" #: ../../extending/extending.rst:874 msgid "" "The macros for checking for a particular object type (``Pytype_Check()``) " "don't check for ``NULL`` pointers --- again, there is much code that calls " "several of these in a row to test an object against various different " "expected types, and this would generate redundant tests. There are no " "variants with ``NULL`` checking." msgstr "" #: ../../extending/extending.rst:880 msgid "" "The C function calling mechanism guarantees that the argument list passed to " "C functions (``args`` in the examples) is never ``NULL`` --- in fact it " "guarantees that it is always a tuple [#old-calling-convention]_." msgstr "" #: ../../extending/extending.rst:884 msgid "" "It is a severe error to ever let a ``NULL`` pointer \"escape\" to the Python " "user." msgstr "" #: ../../extending/extending.rst:895 msgid "Writing Extensions in C++" msgstr "" #: ../../extending/extending.rst:897 msgid "" "It is possible to write extension modules in C++. Some restrictions apply. " "If the main program (the Python interpreter) is compiled and linked by the C " "compiler, global or static objects with constructors cannot be used. This " "is not a problem if the main program is linked by the C++ compiler. " "Functions that will be called by the Python interpreter (in particular, " "module initialization functions) have to be declared using ``extern \"C\"``. " "It is unnecessary to enclose the Python header files in ``extern \"C\" {...}" "`` --- they use this form already if the symbol ``__cplusplus`` is defined " "(all recent C++ compilers define this symbol)." msgstr "" #: ../../extending/extending.rst:911 msgid "Providing a C API for an Extension Module" msgstr "" #: ../../extending/extending.rst:913 msgid "" "Many extension modules just provide new functions and types to be used from " "Python, but sometimes the code in an extension module can be useful for " "other extension modules. For example, an extension module could implement a " "type \"collection\" which works like lists without order. Just like the " "standard Python list type has a C API which permits extension modules to " "create and manipulate lists, this new collection type should have a set of C " "functions for direct manipulation from other extension modules." msgstr "" #: ../../extending/extending.rst:921 msgid "" "At first sight this seems easy: just write the functions (without declaring " "them ``static``, of course), provide an appropriate header file, and " "document the C API. And in fact this would work if all extension modules " "were always linked statically with the Python interpreter. When modules are " "used as shared libraries, however, the symbols defined in one module may not " "be visible to another module. The details of visibility depend on the " "operating system; some systems use one global namespace for the Python " "interpreter and all extension modules (Windows, for example), whereas others " "require an explicit list of imported symbols at module link time (AIX is one " "example), or offer a choice of different strategies (most Unices). And even " "if symbols are globally visible, the module whose functions one wishes to " "call might not have been loaded yet!" msgstr "" #: ../../extending/extending.rst:933 msgid "" "Portability therefore requires not to make any assumptions about symbol " "visibility. This means that all symbols in extension modules should be " "declared ``static``, except for the module's initialization function, in " "order to avoid name clashes with other extension modules. And it means that " "symbols that *should* be accessible from other extension modules must be " "exported in a different way." msgstr "" #: ../../extending/extending.rst:940 msgid "" "Python provides a special mechanism to pass C-level information (pointers) " "from one extension module to another one: Capsules. A Capsule is a Python " "data type which stores a pointer (:c:expr:`void \\*`). Capsules can only be " "created and accessed via their C API, but they can be passed around like any " "other Python object. In particular, they can be assigned to a name in an " "extension module's namespace. Other extension modules can then import this " "module, retrieve the value of this name, and then retrieve the pointer from " "the Capsule." msgstr "" #: ../../extending/extending.rst:948 msgid "" "There are many ways in which Capsules can be used to export the C API of an " "extension module. Each function could get its own Capsule, or all C API " "pointers could be stored in an array whose address is published in a " "Capsule. And the various tasks of storing and retrieving the pointers can be " "distributed in different ways between the module providing the code and the " "client modules." msgstr "" #: ../../extending/extending.rst:954 msgid "" "Whichever method you choose, it's important to name your Capsules properly. " "The function :c:func:`PyCapsule_New` takes a name parameter (:c:expr:`const " "char \\*`); you're permitted to pass in a ``NULL`` name, but we strongly " "encourage you to specify a name. Properly named Capsules provide a degree " "of runtime type-safety; there is no feasible way to tell one unnamed Capsule " "from another." msgstr "" #: ../../extending/extending.rst:961 msgid "" "In particular, Capsules used to expose C APIs should be given a name " "following this convention::" msgstr "" #: ../../extending/extending.rst:964 msgid "modulename.attributename" msgstr "" #: ../../extending/extending.rst:966 msgid "" "The convenience function :c:func:`PyCapsule_Import` makes it easy to load a " "C API provided via a Capsule, but only if the Capsule's name matches this " "convention. This behavior gives C API users a high degree of certainty that " "the Capsule they load contains the correct C API." msgstr "" #: ../../extending/extending.rst:971 msgid "" "The following example demonstrates an approach that puts most of the burden " "on the writer of the exporting module, which is appropriate for commonly " "used library modules. It stores all C API pointers (just one in the " "example!) in an array of :c:expr:`void` pointers which becomes the value of " "a Capsule. The header file corresponding to the module provides a macro that " "takes care of importing the module and retrieving its C API pointers; client " "modules only have to call this macro before accessing the C API." msgstr "" #: ../../extending/extending.rst:979 msgid "" "The exporting module is a modification of the :mod:`!spam` module from " "the :ref:`tutorial `. The function :func:`!" "spam.system` does not call the C library function :c:func:`system` directly, " "but a function :c:func:`!PySpam_System`, which would of course do something " "more complicated in reality (such as adding \"spam\" to every command). This " "function :c:func:`!PySpam_System` is also exported to other extension " "modules." msgstr "" #: ../../extending/extending.rst:987 msgid "" "The function :c:func:`!PySpam_System` is a plain C function, declared " "``static`` like everything else::" msgstr "" #: ../../extending/extending.rst:990 msgid "" "static int\n" "PySpam_System(const char *command)\n" "{\n" " return system(command);\n" "}" msgstr "" #: ../../extending/extending.rst:996 msgid "The function :c:func:`!spam_system` is modified in a trivial way::" msgstr "" #: ../../extending/extending.rst:998 msgid "" "static PyObject *\n" "spam_system(PyObject *self, PyObject *args)\n" "{\n" " const char *command;\n" " int sts;\n" "\n" " if (!PyArg_ParseTuple(args, \"s\", &command))\n" " return NULL;\n" " sts = PySpam_System(command);\n" " return PyLong_FromLong(sts);\n" "}" msgstr "" #: ../../extending/extending.rst:1010 msgid "In the beginning of the module, right after the line ::" msgstr "" #: ../../extending/extending.rst:1014 msgid "two more lines must be added::" msgstr "" #: ../../extending/extending.rst:1016 msgid "" "#define SPAM_MODULE\n" "#include \"spammodule.h\"" msgstr "" #: ../../extending/extending.rst:1019 msgid "" "The ``#define`` is used to tell the header file that it is being included in " "the exporting module, not a client module. Finally, the " "module's :c:data:`mod_exec ` function must take care of " "initializing the C API pointer array::" msgstr "" #: ../../extending/extending.rst:1023 msgid "" "static int\n" "spam_module_exec(PyObject *m)\n" "{\n" " static void *PySpam_API[PySpam_API_pointers];\n" " PyObject *c_api_object;\n" "\n" " /* Initialize the C API pointer array */\n" " PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;\n" "\n" " /* Create a Capsule containing the API pointer array's address */\n" " c_api_object = PyCapsule_New((void *)PySpam_API, \"spam._C_API\", " "NULL);\n" "\n" " if (PyModule_Add(m, \"_C_API\", c_api_object) < 0) {\n" " return -1;\n" " }\n" "\n" " return 0;\n" "}" msgstr "" #: ../../extending/extending.rst:1042 msgid "" "Note that ``PySpam_API`` is declared ``static``; otherwise the pointer array " "would disappear when :c:func:`!PyInit_spam` terminates!" msgstr "" #: ../../extending/extending.rst:1045 msgid "" "The bulk of the work is in the header file :file:`spammodule.h`, which looks " "like this::" msgstr "" #: ../../extending/extending.rst:1048 msgid "" "#ifndef Py_SPAMMODULE_H\n" "#define Py_SPAMMODULE_H\n" "#ifdef __cplusplus\n" "extern \"C\" {\n" "#endif\n" "\n" "/* Header file for spammodule */\n" "\n" "/* C API functions */\n" "#define PySpam_System_NUM 0\n" "#define PySpam_System_RETURN int\n" "#define PySpam_System_PROTO (const char *command)\n" "\n" "/* Total number of C API pointers */\n" "#define PySpam_API_pointers 1\n" "\n" "\n" "#ifdef SPAM_MODULE\n" "/* This section is used when compiling spammodule.c */\n" "\n" "static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;\n" "\n" "#else\n" "/* This section is used in modules that use spammodule's API */\n" "\n" "static void **PySpam_API;\n" "\n" "#define PySpam_System \\\n" " (*(PySpam_System_RETURN (*)PySpam_System_PROTO) " "PySpam_API[PySpam_System_NUM])\n" "\n" "/* Return -1 on error, 0 on success.\n" " * PyCapsule_Import will set an exception if there's an error.\n" " */\n" "static int\n" "import_spam(void)\n" "{\n" " PySpam_API = (void **)PyCapsule_Import(\"spam._C_API\", 0);\n" " return (PySpam_API != NULL) ? 0 : -1;\n" "}\n" "\n" "#endif\n" "\n" "#ifdef __cplusplus\n" "}\n" "#endif\n" "\n" "#endif /* !defined(Py_SPAMMODULE_H) */" msgstr "" #: ../../extending/extending.rst:1096 msgid "" "All that a client module must do in order to have access to the " "function :c:func:`!PySpam_System` is to call the function (or rather " "macro) :c:func:`!import_spam` in its :c:data:`mod_exec ` " "function::" msgstr "" #: ../../extending/extending.rst:1100 msgid "" "static int\n" "client_module_exec(PyObject *m)\n" "{\n" " if (import_spam() < 0) {\n" " return -1;\n" " }\n" " /* additional initialization can happen here */\n" " return 0;\n" "}" msgstr "" #: ../../extending/extending.rst:1110 msgid "" "The main disadvantage of this approach is that the file :file:`spammodule.h` " "is rather complicated. However, the basic structure is the same for each " "function that is exported, so it has to be learned only once." msgstr "" #: ../../extending/extending.rst:1114 msgid "" "Finally it should be mentioned that Capsules offer additional functionality, " "which is especially useful for memory allocation and deallocation of the " "pointer stored in a Capsule. The details are described in the Python/C API " "Reference Manual in the section :ref:`capsules` and in the implementation of " "Capsules (files :file:`Include/pycapsule.h` and :file:`Objects/capsule.c` in " "the Python source code distribution)." msgstr "" #: ../../extending/extending.rst:1122 msgid "Footnotes" msgstr "Fußnoten" #: ../../extending/extending.rst:1123 msgid "" "The metaphor of \"borrowing\" a reference is not completely correct: the " "owner still has a copy of the reference." msgstr "" #: ../../extending/extending.rst:1126 msgid "" "Checking that the reference count is at least 1 **does not work** --- the " "reference count itself could be in freed memory and may thus be reused for " "another object!" msgstr "" #: ../../extending/extending.rst:1131 msgid "" "These guarantees don't hold when you use the \"old\" style calling " "convention --- this is still found in much existing code." msgstr "" #: ../../extending/extending.rst:277 msgid "PyObject_CallObject (C function)" msgstr "" #: ../../extending/extending.rst:372 msgid "PyArg_ParseTuple (C function)" msgstr "" #: ../../extending/extending.rst:499 msgid "PyArg_ParseTupleAndKeywords (C function)" msgstr "" #: ../../extending/extending.rst:520 msgid "Philbrick, Geoff" msgstr ""