Questions tagged [python-c-api]
API used by C and C++ programmers who want to write extension modules or embed Python.
1,190
questions
0
votes
1answer
135 views
Python C API: Access Violation when trying example module with MSVC
I'm making a Python module in C++. Until now I used MingW to compile the module, which worked fine. But I want to switch to MSVC because an other library that I use is easier to use with MSVC.
But, I ...
1
vote
0answers
70 views
Does python multiprocessing call C++ destructors of static variables when the process exits?
Simplified Toy Scenario :
NOTE : This example uses a singleton. One might justifiably question the wisdom in using that, however, for the purposes of this question I would appreciate it if we could ...
0
votes
1answer
20 views
Do the values of global variables in a C extension to Python persist on function calls?
Basically, say I have some global variable foo in my C extension, set to an initial value of 3 like so:
int foo = 3;
And say the value of foo is changed to 4 within function call foobar:
int foobar(...
1
vote
1answer
52 views
C-Extension: Ref count of generators
I'm trying to get the Py_INCREF's and Py_DECREF's for my c extension right.
Whilst doing so I've been stumbling about really high values for generators. What I've
been doing is the following:
// ...
0
votes
1answer
135 views
Python C API crashes on 'import numpy' when initilizing multiple times
While working with the Python C API, I found that the python interpreter crashes when initializing it a second time and executing import numpy after each initilization. Any other command (e.g. import ...
1
vote
0answers
95 views
PyThreadState_SetAsyncExc has no effect
I'm using multiple interpreters with multiple threads, and I'm trying to use PyThreadState_SetAsyncExc to stop a script, but it has no effect:
void stop()
{
PyThreadState *ts = PyThreadState_Swap(...
2
votes
1answer
111 views
Can't resize a tuple using ctypes.pythonapi
Only for testing, I tried to resize a tuple using ctypes, with terrible results:
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" ...
1
vote
0answers
46 views
Python C API - running all python threads in the main thread (or faking it)
I'm adding python scripting support to an application.
This application has an API which is not thread safe, and I cannot change this aspect.
One requirement I have is being able to run multiple ...
2
votes
2answers
1k views
Building a Python-C-Extension on Windows with a debug Python installation
If I build CPython from source on Windows I encounter problems when I want to pip install a package that contains a C-Extension. It seems like the error happens while linking the libraries.
For ...
0
votes
1answer
74 views
CPython 'overloaded' functions
I am trying to overload a python extension function that would take either a object or a string.
typedef struct
{
PyObject_HEAD
} CustomObject;
PyObject* customFunction(CustomObject* self, ...
0
votes
1answer
94 views
Python C API - How to inherit from your own python class?
The newtypes tutorial shows you how to inherit from a base python class. Can you inherit from your own python class? Something like this?
PyObject *mod = PyImport_AddModule("foomod");
PyObject *...
0
votes
1answer
169 views
Creating a PyMemoryView with a specific format
I am exposing a PyMemoryView in C on a set of data, like so:
PyMemoryView_FromMemory((char *)ibuf->rect, pixels * sizeof(uint), PyBUF_WRITE);
That data is floating-point data, however, so ...
2
votes
0answers
45 views
Python C Extension - How to map a Python string to a C Macro Constant?
I'm wrapping a legacy C library. There are a few header files that contains thousands of macro constants like:
#define FOO 1
#define BAR 2
#define BAZ 3
I would like for the user in Python to be ...
1
vote
1answer
74 views
C-API: PySys_SetObject Reference Count
Does PySys_SetObject steal the reference to the object v or should I decrement its reference counter?
PyObject *my_obj = PyUnicode_FromString("my_string_path");
int ret = PySys_SetObject("path", ...
0
votes
1answer
176 views
f2py linking quadmath libraries? Use ctypes for fortran wrapper instead?
Update 11/23/2019:
This started out as a question about why I could not get f2py to work for a simple fortran wrapper. My "answer" (below) is to use ctypes instead.
Original post:
I have spent the ...
0
votes
1answer
110 views
How to call release on a memoryview in Python C API
I have an existing PyMemoryViewObject that I want to "release" to invalidate the memoryview object.
I am able to call the release function through the PyObject_CallMethod API:
if (PyMemoryView_Check(...
0
votes
1answer
120 views
Why does PyLong_AsUnsignedLongLong function fail to convert a numpy.uint64 element, whereas PyLong_AsLongLong succeeds?
I'm working on a C-extension for Python which implements a method that converts a list of numpy elements (numpy.uint64 in this case) to the unsigned long long C-type (using the ...
0
votes
0answers
181 views
How to properly send a CuPy array to a Python C-extension module
I'm trying to write a custom CXX extension for Python which takes CuPy arrays as input. What's the recommended way to hand off and return CuPy arrays from a CXX extension?
My current approach is to ...
1
vote
1answer
409 views
Is it possible in pybind11 to use py::cast to access an abstract base class?
I have include a minimal working example below - it can be compiled using the typical pybind11 instructions (I use cmake).
I have an abstract base class, Abstract, which is pure virtual. I can easily ...
1
vote
1answer
110 views
Python CExtension gives ModuleNotFoundError
I am using Python 3 with Anaconda Spyder on CentOS 7. I am trying to get the Python CExtension working by following this video.
https://www.youtube.com/watch?v=a65JdvOaygM
I have all of my files ...
-1
votes
1answer
46 views
Wrong first argument when using PyArg_ParseTuple
I write methods for a c extension type:
static PyObject *
RawGraphState_apply_C_L(RawGraphState * self
, PyObject * args)
{
npy_uint8 vop = 0xdeadbeef;
npy_intp i;// = ...
0
votes
0answers
72 views
Writing the result of a converted code to a plain text file
I am embedding Python in a Larger C++ application using the Python C API. My goal is to make a game that can teach programming using Python, and the player actually types in Python Code, which is why ...
0
votes
2answers
544 views
Build a PyObject* with a C Object pointer
Say I have this struct:
typedef struct
{
PyObject_HEAD
Foo* myFoo;
} PyFoo;
Let's just say that Foo is:
class Foo
{
public:
hello()
{
std::cout << "Hello\n";
}
};
I don't want ...
-1
votes
1answer
74 views
How to convert PyObjects to C data types?
I am working on a project where I have to convert a user input C++ string variable to python executable code, I'm using the Python C API, so I have to go through the intermediary of converting the C++ ...
0
votes
1answer
113 views
PyFunctionObject crash the programm in Py_Finalize if it has being set item in PyTuple
I need get list of function name and signatures by python file.
Python function inspect.signature can get me function signature.
But inspect.signature need a function object (PyFunctionObject).
...
-1
votes
1answer
51 views
build C extension for python——'undefined reference to _Py_GC_generation0'
The background information is that I want to implement my own HashMap object by pyhton for C extension.
But When I finished 'hashmap.c' and used 'distutils' to compile it as a module, I found ...
0
votes
1answer
47 views
A problem in manually reproducing dict underlying code:the value can't be object
I tried to manually reproduce python dict underlying code(it can only implement setitem and getitem), but I met a problem: The hashmap I wrote can only work well when the value type is basic data ...
2
votes
0answers
59 views
Documenting a Python C Extension on ReadTheDocs
I have a Python package including a couple C extensions whose documentation I would like to host on ReadTheDocs, but the build fails, apparently because the C extensions are not being compiled. The C ...
2
votes
1answer
85 views
Subdirectory structure breaks C++ extension build [duplicate]
I can't seem to get around a problem where importing a C++ extension module no longer works when a subdirectory structure is used.
The two cases below present a simple working case and a slightly ...
3
votes
1answer
132 views
Is incrementing Py_True/Py_False refcount always necessary?
I'm new to the Python C-API and browsing through some source code to pick parts of it up.
Here is a minimal version of a function that I found, in the C source of a package that contains extension ...
3
votes
1answer
143 views
Implementing unit tests for a Python C Extension
So, I have a repo to build a python C extension laid out as follows:
setup.py
demo.c
MANIFEST.in
The contents of the C file are:
#include <Python.h>
static PyObject* print_message(PyObject* ...
0
votes
0answers
93 views
linking a dll does not link in .lib files and expects other the .dll form
I'm trying to build a python c extension on windows with msvc (using distutils) which links in some other static libraries.
Basically I have test1.lib, test2.lib and test3.obj and want to build test4....
6
votes
1answer
702 views
How to list all function names of a Python module in C++?
I have a C++ program, I want to import a Python module and list all function names in this module. How can I do it?
I used the following code to get the dict from a module:
PyDictObject* pDict = (...
4
votes
1answer
483 views
Embedding Python in C/C++
For my senior project in Computer Science, I am making a puzzle video game that will teach people how to code in Python. The largest portion of the design involves creating engaging puzzles that the ...
2
votes
1answer
87 views
Member assignment and ref counting in __init__
I'm writing a C extension for Python and going through the documentation, I'm having a hard time understanding member assignment in the __init__ function.
So there, in section 2.2, member assignment ...
2
votes
2answers
154 views
INCREF needed when returning argument from Python C Extension function?
This question is pretty simple but will help cement my understanding. I know that arguments to C extension functions are guaranteed to be live references for the duration of the C code (unless ...
0
votes
1answer
278 views
Numpy with PyPy problems
I'm trying to install numpy and other packages with PyPy. I get the error: "error: Microsoft Visual C++ 14.1 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft....
-1
votes
1answer
40 views
Do Python C Extensions release the GIL for CPU tasks as they do for IO tasks?
Python C Extensions always release the GIL via Py_BEGIN_ALLOW_THREADS when making IO system calls. I have read mixed opinions on whether C Extensions release the GIL for relatively long running CPU-...
1
vote
1answer
38 views
numpy nd array layout in memory
Transposing an ndarry does not change the actually layout in memory
i.e. after transpose the ndarry is not 'C' order anymore
I wrote a cpp extension for numpy tasks thus if the order the dimensions ...
2
votes
0answers
63 views
Link against another python C extension
I have two python extensions written in C:
foo.bar.libbar defined in foo/bar/bar.c
foo.baz.libbaz defined in foo/baz/baz.c
libbar depends on symbols from libbaz, namely a non-python-exported ...
0
votes
1answer
259 views
How to use python “include” and “libs” path in a windows makefile to compile all python embedded C++ program in a folder?
Makefile specified in this question, compiling all the cpp programs in a folder but not with python embedded cpp programs.
all: myUB
sourcesC := $(wildcard ../src/*.cpp)
objectsC := $(patsubst %....
2
votes
1answer
92 views
What does 'PYVERNODOTS' in Python C-extension modules mean? [closed]
When I want to compile Python C-extension modules on Linux, the file name of the compiled modules is for example <name-of-module>.cpython-@PYVERNODOTS@m-x86_64-linux-gnu.so. However this only ...
1
vote
1answer
215 views
C-Numpy: How to create fixed-width ndarray of strings from existing data
I'm writing a Python extension module in C++ with Boost Python. I want to return numpy arrays from the module to Python. It works well with numeric datatypes like double but at one point I need to ...
0
votes
1answer
346 views
Memory Leak in C-extension for Python
This is the first time I am writing a C-extension for python and you can see my ugly and probably super inefficient C++ implementation of a convolution. I have a problem with the memory management. ...
3
votes
1answer
1k views
How do I check if a PyObject is a list?
I am new to the Python/C API and while I got some basic functions to work, I am struggling with this one.
PyObject* sum_elements(PyObject*, PyObject *o)
{
Py_ssize_t n = PyList_Size(o);
...
0
votes
1answer
153 views
Import module after Py_Initialize
Today, I use PyImport_AppendInittab to append python modules built in C. PyImport_AppendInittab needs to be called before Py_Initialize. I can't finalize and then initialize the engine again. The ...
1
vote
1answer
64 views
Iterating over ndarray columns in C/C++
How would one get a view of a PyArrayObject* similar to the following python code?
# n-column array x
# d is the length of each column
print(x.shape) # => (d, n)
by_column = [x[::,i] for i in ...
2
votes
1answer
81 views
NumPy C API extension causes excessive memory usage
I have written a C extension to NumPy to speed up some of my calculations, but I am getting increasing memory usage as I call the function repeatedly. I have trimmed down the function into a minimum ...
2
votes
0answers
272 views
embedded python hangs on import site-package
I'm trying to embed python in a c/c++ application, using the embedded python zip file. I also want to use site-packages, like numpy. I manipulate the sys path myself, so it'll include all paths ...
0
votes
1answer
63 views
Why Python IDLE crash with error StackHash_0a9e?
My code compares 2 lists of tuples and displays "True" if the all elements of the first tuple are in the range of the second tuple. The range is set by the argument "ar".
#include <Python.h>
...