python-c-api

Accessing view of a NumPy array using the C API

断了今生、忘了曾经 提交于 2019-12-05 12:53:42
In a Python extension module I've written in C++, I use the following snippet of code to convert a NumPy array into an Armadillo array for use in the C++ portion of the code: static arma::mat convertPyArrayToArma(PyArrayObject* pyarr, int nrows, int ncols) { // Check if the dimensions are what I expect. if (!checkPyArrayDimensions(pyarr, nrows, ncols)) throw WrongDimensions(); const std::vector<int> dims = getPyArrayDimensions(pyarr); // Gets the dimensions using the API PyArray_Descr* reqDescr = PyArray_DescrFromType(NPY_DOUBLE); if (reqDescr == NULL) throw std::bad_alloc(); // Convert the

Python C-API access String constants

独自空忆成欢 提交于 2019-12-05 09:52:58
I wanted to implement a library I have written for python in C using the C-API of python. In python I can declare "constants" in my module by just stating: RED = "red" # Not really a constant, I know BLUE = "blue" # but suitable, nevertheless def solve(img_h): # Awesome computations return (RED, BLUE)[some_flag] Those constants are then later returned by the functions offered by the module. I have some trouble doing the same thing in C. Here is what I got so far: PyMODINIT_FUNC PyInit_puzzler(void) { PyObject* module = PyModule_Create(&Module); (void) PyModule_AddStringConstant(module, "BLUE",

NumPy C-API: convert type object to type number

本秂侑毒 提交于 2019-12-05 07:28:50
The function PyObject* PyArray_TypeObjectFromType(int); converts the type number for a NumPy scalar type (NPY_BOOL, NPY_BYTE, ...) to the corresponding type object. How do you do the opposite conversion, from the type object for a NumPy scalar type to the corresponding type number? Edit: The following code is based on kwatford's answer. It accepts both type objects such as int and numpy.int16, and strings such as "int", u"int" and "int16". int numpyScalarTypeNumber(PyObject* obj) { PyArray_Descr* dtype; if(!PyArray_DescrConverter(obj, &dtype)) return NPY_NOTYPE; int typeNum = dtype->type_num;

Limitations of PyTuple_SetItem

别说谁变了你拦得住时间么 提交于 2019-12-05 02:15:28
I have a Python extension module which creates a tuple as an attribute of another object, and sets items in the tuple. Whenever I execute this module in Python, I keep getting the error SystemError: bad argument to internal function After reading over the docs for PyTuple , and debugging my program for a few hours, I still couldn't figure out what the hell was going on. Running my program through a debugger indicated the problem was occurring within a library call inside the Python interpreter. So, finally, I looked at the Python source code, and at long last I realized the problem. The

Does the Python 3 interpreter leak memory when embedded?

泄露秘密 提交于 2019-12-05 01:24:09
问题 This bug report states that the Python interpreter, as of June 2007, will not clean up all allocated memory after calling Py_Finalize in a C/C++ application with an embedded Python interpreter. It was recommended to call Py_Finalize once at application termination. This bug report states that as of version 3.3 and March 2011 the interpreter still leaks memory. Does anyone know the current state of this issue? I am concerned because I have an application in which the interpreter is called

“AttributeError: 'module' object has no attribute 'argv'” when using Python.h

给你一囗甜甜゛ 提交于 2019-12-05 01:13:00
When messing around with Python.h I got this error: AttributeError: 'module' object has no attribute 'argv' C++ code: #include "stdafx.h" #include "C:/Python27/include/Python.h" #include <iostream> using namespace std; int main() { Py_Initialize(); PyRun_SimpleString("import sys\nprint sys.argv[0]"); } Which in Python is: import sys print sys.argv[0] What am I missing? Conceptually, sys.argv should contain the arguments that Python was called with (and what it was called under). What should it have if it were called like this, though? You can load the calling program's argv into sys , if you

How is __slots__ implemented in Python?

别等时光非礼了梦想. 提交于 2019-12-05 00:36:23
How is __slots__ implemented in Python? Is this exposed in the C interface ? How do I get __slots__ behaviour when defining a Python class in C via PyTypeObject ? When creating Python classes, they by default have a __dict__ and you can set any attribute on them. The point of slots is to not create a __dict__ to save space. In the C interface it's the other way around, an extension class has by default no __dict__ , and you would instead explicitly have to add one and add getattr/setattr support to handle it (although luckily there are methods for this already, PyObject_GenericGetAttr and

PyObject_CallMethod with keyword arguments

雨燕双飞 提交于 2019-12-04 22:28:11
问题 I'm trying to embed a Python (2.7) library in my C application and I'm using the Python/C API to call Python code from C. I need to call a Python method that takes keyword arguments. Semantically, I'm trying to achieve the equivalent of the following line in Python: myobject.dosomething('blahdy blah', somearg=True) By reading the documentation, I have managed to get as far as the following, but this doesn't pass in the keyword arguments: PyObject_CallMethod(myobject, "dosomething", "s",

How to extend/reuse Python C Extensions/API implementation?

馋奶兔 提交于 2019-12-04 20:37:47
The problem is that now, I have to use the Posix C getline function to get the line from the file, only then convert it to a Python Unicode Object using PyUnicode_DecodeUTF8 and cache it using my caching policy algorithm. This process is losing 23% of performance compared to Python builtin for line in file C implementation. If I remove the PyUnicode_DecodeUTF8 call from my code, then, my implementation using the Posix C getline becomes 5% faster than the Python builtin for line in file C implementation. So, if I can just make Python directly give me a Python Unicode String object, instead of

Parsing User Defined Types Using PyArg_ParseTuple

旧巷老猫 提交于 2019-12-04 13:46:42
How to parse userdefined types (or types from an existing non-standard library) using PyArg_ParseTuple ? Instead of using the plain O format, as Martijn suggested, I normally prefer using the O& format . It allows you to pass a function that will be called to convert any PyObject* to an arbitrary C (double) pointer. Here is some example usage, in which I'm converting a passed value to a pointer to my own object type: /** * This method should return 0 if it does not work or 1 in case it does * PyArg_*() functions will handle the rest from there or let your program * continue in case things are