- How do I call an object's method from C?
- ========================================
- The "PyObject_CallMethod()" function can be used to call an arbitrary
- method of an object. The parameters are the object, the name of the
- method to call, a format string like that used with "Py_BuildValue()",
- and the argument values:
- PyObject *
- PyObject_CallMethod(PyObject *object, const char *method_name,
- const char *arg_format, ...);
- This works for any object that has methods -- whether built-in or
- user-defined. You are responsible for eventually "Py_DECREF()"'ing the
- return value.
- To call, e.g., a file object's "seek" method with arguments 10, 0
- (assuming the file object pointer is "f"):
- res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
- if (res == NULL) {
- ... an exception occurred ...
- }
- else {
- Py_DECREF(res);
- }
- Note that since "PyObject_CallObject()" *always* wants a tuple for the
- argument list, to call a function without arguments, pass "()" for the
- format, and to call a function with one argument, surround the
- argument in parentheses, e.g. "(i)".
- How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?
- ========================================================================================
- In Python code, define an object that supports the "write()" method.
- Assign this object to "sys.stdout" and "sys.stderr". Call
- print_error, or just allow the standard traceback mechanism to work.
- Then, the output will go wherever your "write()" method sends it.
- The easiest way to do this is to use the "io.StringIO" class:
- >>> import io, sys
- >>> sys.stdout = io.StringIO()
- >>> print('foo')
- >>> print('hello world!')
- >>> sys.stderr.write(sys.stdout.getvalue())
- foo
- hello world!
- A custom object to do the same would look like this:
- >>> import io, sys
- >>> class StdoutCatcher(io.TextIOBase):
- ... def __init__(self):
- ... self.data = []
- ... def write(self, stuff):
- ... self.data.append(stuff)
- ...
- >>> import sys
- >>> sys.stdout = StdoutCatcher()
- >>> print('foo')
- >>> print('hello world!')
- >>> sys.stderr.write(''.join(sys.stdout.data))
- foo
- hello world!
- How do I access a module written in Python from C?
- ==================================================
- You can get a pointer to the module object as follows:
- module = PyImport_ImportModule("<modulename>");
- If the module hasn't been imported yet (i.e. it is not yet present in
- "sys.modules"), this initializes the module; otherwise it simply
- returns the value of "sys.modules["<modulename>"]". Note that it
- doesn't enter the module into any namespace -- it only ensures it has
- been initialized and is stored in "sys.modules".
- You can then access the module's attributes (i.e. any name defined in
- the module) as follows:
- attr = PyObject_GetAttrString(module, "<attrname>");
- Calling "PyObject_SetAttrString()" to assign to variables in the
- module also works.
- How do I interface to C++ objects from Python?
- ==============================================
- Depending on your requirements, there are many approaches. To do this
- manually, begin by reading the "Extending and Embedding" document.
- Realize that for the Python run-time system, there isn't a whole lot
- of difference between C and C++ -- so the strategy of building a new
- Python type around a C structure (pointer) type will also work for C++
- objects.
- For C++ libraries, see Writing C is hard; are there any alternatives?.
- Related video: Unleash The Power of C++ In Python
Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.
Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license