python-c-api

Python C extension: method signatures for documentation?

ⅰ亾dé卋堺 提交于 2019-11-30 01:46:11
问题 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

File I/O in the Python 3 C API

随声附和 提交于 2019-11-29 18:59:18
问题 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? 回答1: You can do it the old(new?)-fashioned way, by just calling the io module. This code works, but it does no error

How to return an C array to Python?

試著忘記壹切 提交于 2019-11-29 16:00:01
I wrote a Python/C extension function that was called by Python, How can return an 2d array int[][] to Python? static PyObject* inference_function(PyObject *self, PyObject *args) { PyObject* doc_lst; int K,V; double alpha,beta; int n_iter; if (!PyArg_ParseTuple(args, "Oiiddi", &doc_lst, &K,&V, &alpha,&beta,&n_iter)) { printf("传入参数错误!\n"); return NULL; } return Py_BuildValue("i", 1); } What kind of array are you using? One way, which I find convenient, is to use numpy arrays, and modify the data in place. Numpy already has a lot of great operations for manipulating integer arrays, so this is

numpy array C api

天涯浪子 提交于 2019-11-29 14:14:19
问题 I have a C++ function returning a std::vector and I want to use it in python, so I'm using the C numpy api: static PyObject * py_integrate(PyObject *self, PyObject *args){ ... std::vector<double> integral; cpp_function(integral); // This changes integral npy_intp size = {integral.size()}; PyObject *out = PyArray_SimpleNewFromData(1, &size, NPY_DOUBLE, &(integral[0])); return out; } Here's how I call it from python: import matplotlib.pyplot as plt a = py_integrate(parameters) print a fig = plt

Define a global in a Python module from a C API

冷暖自知 提交于 2019-11-29 07:49:37
I am developing a module for Python using a C API. How can I create a variable that is seen as global from Python? For example, if my module is module , I want to create a variable g that does this job: import module print module.g In particular, g is an integer. Solution from Alex Martelli PyObject *m = Py_InitModule("mymodule", mymoduleMethods); PyObject *v = PyLong_FromLong((long) 23); PyObject_SetAttrString(m, "g", v); Py_DECREF(v); You can use PyObject_SetAttrString in your module's initialization routine, with first argument o being (the cast to (PyObject*) of) your module, second

Multithreading with Python and C api

不打扰是莪最后的温柔 提交于 2019-11-28 23:50:19
I have a C++ program that uses the C api to use a Python library of mine. Both the Python library AND the C++ code are multithreaded. In particular, one thread of the C++ program instantiates a Python object that inherits from threading.Thread . I need all my C++ threads to be able to call methods on that object. From my very first tries (I naively just instantiate the object from the main thread, then wait some time, then call the method) I noticed that the execution of the Python thread associated with the object just created stops as soon as the execution comes back to the C++ program. If

C Python: Running Python code within a context

不问归期 提交于 2019-11-28 21:27:45
The Python C API function PyEval_EvalCode let's you execute compiled Python code. I want to execute a block of Python code as if it were executing within the scope of a function , so that it has its own dictionary of local variables which don't affect the global state. This seems easy enough to do, since PyEval_EvalCode lets you provide a Global and Local dictionary: PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) The problem I run into has to do with how Python looks up variable names. Consider the following code, that I execute with PyEval_EvalCode : myvar =

Calling python method from C++ (or C) callback

孤街醉人 提交于 2019-11-28 17:49:11
问题 I am trying to call methods in a python class from C++. The C++ method from which this is called is a C++ callback. Within this method when I am trying to call python method, it was giving segmentation fault . I have saved an instance of python function in a global variable like // (pFunc is global variable of type PyObject*) pFunc = PyDict_GetItemString(pDict, "PlxMsgWrapper"); where PlxMsgWrapper is a python method, which will be used in the callback. In the callback, the arguments are

Py_INCREF/DECREF: When

浪尽此生 提交于 2019-11-28 15:59:20
Is one correct in stating the following: If a Python object is created in a C function, but the function doesn't return it, no INCREF is needed, but a DECREF is. [false]If the function does return it, you do need to INCREF , in the function that receives the return value.[/false] When assigning C typed variables as attributes, like double , int etc., to the Python object, no INCREF or DECREF is needed. Assigning Python objects as attributes to your other Python objects goes like this: PyObject *foo; foo = bar // A Python object tmp = self->foo; Py_INCREF(foo); self->foo = foo; Py_XDECREF(tmp);

How to create a generator/iterator with the Python C API?

北战南征 提交于 2019-11-28 15:43:34
How do I replicate the following Python code with the Python C API? class Sequence(): def __init__(self, max): self.max = max def data(self): i = 0 while i < self.max: yield i i += 1 So far, I have this: #include <Python/Python.h> #include <Python/structmember.h> /* Define a new object class, Sequence. */ typedef struct { PyObject_HEAD size_t max; } SequenceObject; /* Instance variables */ static PyMemberDef Sequence_members[] = { {"max", T_UINT, offsetof(SequenceObject, max), 0, NULL}, {NULL} /* Sentinel */ }; static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds) { if