python-c-api

Creating an inheritable Python type with PyCxx

A friend and I have been toying around with various Python C++ wrappers lately, trying to find one that meets the needs of both some professional and hobby projects. We've both honed in on PyCxx as a good balance between being lightweight and easy to interface with while hiding away some of the ugliest bits of the Python C api. PyCxx is ...

Python c-api and unicode strings

I need to convert between python objects and c strings of various encodings. Going from a c string to a unicode object was fairly simple using PyUnicode_Decode, however Im not sure how to go the other way //char* can be a wchar_t or any other element size, just make sure it is correctly terminated for its encoding Unicode(const char *st...

Python C-API Object Allocation‏

I want to use the new and delete operators for creating and destroying my objects. The problem is python seems to break it into several stages. tp_new, tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc for destruction. However c++ just has new which allocates and fully constructs the object and delete which destructs ...

Any way to create a NumPy matrix with C API?

I read the documentation on NumPy C API I could find, but still wasn't able to find out whether there is a possibility to construct a matrix object with C API — not a two-dimensional array. The function is intended for work with math matrices, and I don't want strange results if the user calls matrix multiplication forgetting to convert ...

Python C-API Object Initialisation

What is the correct way to initialise a python object into already existing memory (like the inplace new in c++) I tried this code however it causes an access violation with a debug build because the _ob_prev and _ob_next are not set.. //PyVarObject *mem; -previously allocated memory Py_INCREF(type); //couldnt get PyObject_HEAD_INIT o...

File I/O in the Python 3 C API

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 b...

Python Extension Returned Object Etiquette

I am writing a python extension to provide access to Solaris kstat data ( in the same spirit as the shipping perl library Sun::Solaris::Kstat ) and I have a question about conditionally returning a list or a single object. The python use case would look something like: cpu_stats = cKstats.lookup(module='cpu_stat') cpu_stat0 = ...

Python C API: how to get string representation of exception?

If I do (e.g.) open("/snafu/fnord") in Python (and the file does not exist), I get a traceback and the message IOError: [Errno 2] No such file or directory: '/snafu/fnord' I would like to get the above string with Python's C API (i.e., a Python interpreter embedded in a C program). I need it as a string, not output to the console...

Accessing Python Objects in a Core Dump

Is there anyway to discover the python value of a PyObject* from a corefile in gdb ...

Python C extension: method signatures for documentation?

Hello SO :) I am writing C extensions, and I'd like to specify for my users the signature of my methods. Let's throw in some code :) static PyObject* foo(PyObject *self, PyObject *args) { /* blabla [...] */ } PyDoc_STRVAR( foo_doc, "Great example function\n" "Arguments: (timeout, flags=None)\n" "Doc blahblah doc ...

Stopping embedded Python

I'm embedding Python interpreter to a C program. However, it might happen that while running some python script via PyRun_SimpleString() will run into infinite loop or execute for too long. Consider PyRun_SimpleString("while 1: pass"); In preventing the main program to block I thought I could run the interpreter in a thread. How do I st...

Why does Python keep a reference count on False and True?

I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest: Py_INCREF(Py_False); return Py_False; ... Py_INCREF(Py_True); return Py_True; Aren't Py_False and Py_True global values? Just out of sheer curiosity, why is Python keeping a reference count for these variables? ...

Python interpreter as a c++ class

I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread. Can I wrap Python interpreter in to a c++ class and get services from two or more class instances? ...

PyDateTime_IMPORT macro not initializing PyDateTimeAPI variable

I'm using the Python C API on Windows using Visual Studio 2008. When I attempt to use the PyDate_Check macro, and other related macros, they cause an access violation because the static variable PyDateTimeAPI is null. This variable is initialized using the PyDateTime_IMPORT macro which needs calling before using any date time macros. I d...

Explanation of PyAPI_DATA() macro?

I've searched all over the web and can't seem to find documentation or even a simple explanation of what PyAPI_DATA() does (even though it is used in the Python header files and cited on python.org). Could anyone care to explain what this is or point me to documentation I am overlooking? Thanks. ...

How to pass flag to gcc in Python setup.py script?

I'm writing a Python extension in C that requires the CoreFoundation framework (among other things). This compiles fine with: gcc -o foo foo.c -framework CoreFoundation -framework Python ("-framework" is an Apple-only gcc extension, but that's okay because I'm using their specific framework anyway) How do I tell setup.py to pass this...

Nested Python C Extensions/Modules?

How do I compile a C-Python module such that it is local to another? E.g. if I have a module named "bar" and another module named "mymodule", how do I compile "bar" so that it imported via "import mymodule.bar"? (Sorry if this is poorly phrased, I wasn't sure what the proper term for it was.) I tried the following in setup.py, but it d...

How to import a file by its full path using C api?

Hello PyObject* PyImport_ImportModule( const char *name) How to specify a full file path instead and a module name? Like PyImport_SomeFunction(const char *path_to_script, const char *name) Thanks, Elias ...

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

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 ne...

Named parameters with Python C API?

How can I simulate the following Python function using the Python C API? def foo(bar, baz="something or other"): print bar, baz (i.e., so that it is possible to call it via: >>> foo("hello") hello something or other >>> foo("hello", baz="world!") hello world! >>> foo("hello", "world!") hello, world! ) ...