The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Python FAQ. How do I call an object s method from C? Unleash The Power of C++ In Python
By Guest on 7th November 2022 08:22:04 AM | Syntax: PYTHON | Views: 174



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1. How do I call an object's method from C?
  2. ========================================
  3.  
  4. The "PyObject_CallMethod()" function can be used to call an arbitrary
  5. method of an object.  The parameters are the object, the name of the
  6. method to call, a format string like that used with "Py_BuildValue()",
  7. and the argument values:
  8.  
  9.   PyObject *
  10.   PyObject_CallMethod(PyObject *object, const char *method_name,
  11.                       const char *arg_format, ...);
  12.  
  13. This works for any object that has methods -- whether built-in or
  14. user-defined. You are responsible for eventually "Py_DECREF()"'ing the
  15. return value.
  16.  
  17. To call, e.g., a file object's "seek" method with arguments 10, 0
  18. (assuming the file object pointer is "f"):
  19.  
  20.   res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
  21.   if (res == NULL) {
  22.           ... an exception occurred ...
  23.   }
  24.   else {
  25.           Py_DECREF(res);
  26.   }
  27.  
  28. Note that since "PyObject_CallObject()" *always* wants a tuple for the
  29. argument list, to call a function without arguments, pass "()" for the
  30. format, and to call a function with one argument, surround the
  31. argument in parentheses, e.g. "(i)".
  32.  
  33.  
  34. How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?
  35. ========================================================================================
  36.  
  37. In Python code, define an object that supports the "write()" method.
  38. Assign this object to "sys.stdout" and "sys.stderr".  Call
  39. print_error, or just allow the standard traceback mechanism to work.
  40. Then, the output will go wherever your "write()" method sends it.
  41.  
  42. The easiest way to do this is to use the "io.StringIO" class:
  43.  
  44.   >>> import io, sys
  45.   >>> sys.stdout = io.StringIO()
  46.   >>> print('foo')
  47.   >>> print('hello world!')
  48.   >>> sys.stderr.write(sys.stdout.getvalue())
  49.   foo
  50.   hello world!
  51.  
  52. A custom object to do the same would look like this:
  53.  
  54.   >>> import io, sys
  55.   >>> class StdoutCatcher(io.TextIOBase):
  56.   ...     def __init__(self):
  57.   ...         self.data = []
  58.   ...     def write(self, stuff):
  59.   ...         self.data.append(stuff)
  60.   ...
  61.   >>> import sys
  62.   >>> sys.stdout = StdoutCatcher()
  63.   >>> print('foo')
  64.   >>> print('hello world!')
  65.   >>> sys.stderr.write(''.join(sys.stdout.data))
  66.   foo
  67.   hello world!
  68.  
  69.  
  70. How do I access a module written in Python from C?
  71. ==================================================
  72.  
  73. You can get a pointer to the module object as follows:
  74.  
  75.   module = PyImport_ImportModule("<modulename>");
  76.  
  77. If the module hasn't been imported yet (i.e. it is not yet present in
  78. "sys.modules"), this initializes the module; otherwise it simply
  79. returns the value of "sys.modules["<modulename>"]".  Note that it
  80. doesn't enter the module into any namespace -- it only ensures it has
  81. been initialized and is stored in "sys.modules".
  82.  
  83. You can then access the module's attributes (i.e. any name defined in
  84. the module) as follows:
  85.  
  86.    attr = PyObject_GetAttrString(module, "<attrname>");
  87.  
  88. Calling "PyObject_SetAttrString()" to assign to variables in the
  89. module also works.
  90.  
  91.  
  92. How do I interface to C++ objects from Python?
  93. ==============================================
  94.  
  95. Depending on your requirements, there are many approaches.  To do this
  96. manually, begin by reading the "Extending and Embedding" document.
  97. Realize that for the Python run-time system, there isn't a whole lot
  98. of difference between C and C++ -- so the strategy of building a new
  99. Python type around a C structure (pointer) type will also work for C++
  100. objects.
  101.  
  102. For C++ libraries, see Writing C is hard; are there any alternatives?.
  103.  
  104.  
  105. 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
  • Recent Pastes