python-c-api

How do I properly use Python's C API and exceptions?

北慕城南 提交于 2019-11-30 22:53:38
问题 if I do something like >>> x = int(1,2,3,4,5) I immediately get a fatal error (one that would end program execution if it was in a pre-written script) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: int() takes at most 2 arguments (5 given) and x remains undefined: >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined How would I go about implementing that in Python's C API? I found some documentation

(Python C API) PyRun_StringFlags missing builtin functions?

好久不见. 提交于 2019-11-30 18:29:41
I am trying to embed some python in my pet project. I have reduced my problem to the following code: #include <Python.h> #include "iostream" int main(int argc, char *argv[]) { Py_Initialize(); PyObject *globals = Py_BuildValue("{}"); PyObject *locals = Py_BuildValue("{}"); PyObject *string_result = PyRun_StringFlags( "a=5\n" "s='hello'\n" "d=dict()\n" , Py_file_input, globals, locals, NULL); if ( PyErr_Occurred() ) {PyErr_Print();PyErr_Clear();return 1;} return 0; } (I know I'm not cleaning up any references. This is an example.) it can be compiled by c++ $(python-config --includes) $(python

Python C extension: method signatures for documentation?

家住魔仙堡 提交于 2019-11-30 17:45:33
I am writing C extensions, and I'd like to make the signature of my methods visible for introspection. static PyObject* foo(PyObject *self, PyObject *args) { /* blabla [...] */ } PyDoc_STRVAR( foo_doc, "Great example function\n" "Arguments: (timeout, flags=None)\n" "Doc blahblah doc doc doc."); static PyMethodDef methods[] = { {"foo", foo, METH_VARARGS, foo_doc}, {NULL}, }; PyMODINIT_FUNC init_myexample(void) { (void) Py_InitModule3("_myexample", methods, "a simple example module"); } Now if (after building it...) I load the module and look at its help: >>> import _myexample >>> help(

How can I reference #defines in a C file from python?

爱⌒轻易说出口 提交于 2019-11-30 15:15:54
问题 I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it. Edit: These are very simple #defines that define the meanings of bits in a mask, for example: #define FOO_A 0x3

Create instance of a python class , declared in python, with C API

为君一笑 提交于 2019-11-30 15:15:17
问题 I want to create an instance of a Python class defined in the __main__ scope with the C API. For example, the class is called MyClass and is defined as follows: class MyClass: def __init__(self): pass The class type lives under __main__ scope. Within the C application, I want to create an instance of this class. This could have been simply possible with PyInstance_New as it takes class name. However this function is not available in Python3. Any help or suggestions for alternatives are

embedding python

自古美人都是妖i 提交于 2019-11-30 15:14:21
问题 Im trying to call python functions from C code, and i followed a sample from here I also have the correct include file directries, library directries, and linked the python32.lib (im using python 32) however the error was that python/C APIs such as PyString_FromString, PyInt_FromLong, PyInt_AsLong are undefined (error in the debugger) this is strange because im also using other APIs, but they're all fine... whats the problem here?? int main(int argc, char *argv[]) { PyObject *pName, *pModule,

File I/O in the Python 3 C API

99封情书 提交于 2019-11-30 14:16:08
The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects. Before, in 2.X, you could use PyObject* PyFile_FromString(char *filename, char *mode) to create a Python file object, e.g: PyObject *myFile = PyFile_FromString("test.txt", "r"); ...but such function no longer exists in Python 3.0. What would be the Python 3.0 equivalent to such call? You can do it the old(new?)-fashioned way, by just calling the io module. This code works, but it does no error checking. See the docs for explanation. PyObject *ioMod, *openedFile; PyGILState_STATE gilState = PyGILState

Python: GIL context - switching

此生再无相见时 提交于 2019-11-30 13:42:38
So, I generally have a pretty good understanding of how the Global Interpreter Lock (GIL) in Python works. Essentially, while the interpreter is running, one thread holds the GIL for N ticks (where N can be set using sys.setcheckinterval ), at which point the GIL is released and another thread can acquire the GIL. The also happens if one thread begins an I/O operation. What I'm a bit confused about is how this all works with C extension modules. If you have a C extension module that acquires the GIL, and then executes some python code using PyEval_EvalCode , can the interpreter release the GIL

Suggestions on how to speed up a distance calculation

久未见 提交于 2019-11-30 09:53:14
Consider the following class: class SquareErrorDistance(object): def __init__(self, dataSample): variance = var(list(dataSample)) if variance == 0: self._norm = 1.0 else: self._norm = 1.0 / (2 * variance) def __call__(self, u, v): # u and v are floats return (u - v) ** 2 * self._norm I use it to calculate the distance between two elements of a vector. I basically create one instance of that class for every dimension of the vector that uses this distance measure (there are dimensions that use other distance measures). Profiling reveals that the __call__ function of this class accounts for 90%

Python C-API functions that borrow and steal references

微笑、不失礼 提交于 2019-11-30 08:56:24
The standard convention in the Python C-API is that functions do not steal references from input arguments (that are objects) return values and output arguments (that are objects) own a reference Most functions in the Python C-API follow this convention. However, there are some exceptions. I have come across the following: Functions that steal a reference from an input argument PyModule_AddObject Functions with return values or output arguments that borrow a reference PyErr_Occurred PyTuple_GetItem PyTuple_GETITEM PyDict_GetItem PyDict_GetItemString PyDict_Next Is there a comprehensive list of