Questions tagged [python-c-api]
API used by C and C++ programmers who want to write extension modules or embed Python.
1,284
questions
0
votes
0
answers
19
views
C/Python API unable to import PIL.Image
I am running Python scripts from a C++ application. One of the scripts I am using imports PIL.Image:
import os
import json
import boto3
import PIL.Image
import PIL.ExifTags
When I call this script, ...
0
votes
0
answers
36
views
PyArg_Parse for multiple returns of python on c++
I am calling python from c++ using PyObject_CallObject
as the python return only a floating point number, i can get it by:
float output_of_python;
PyObject *pValue,*pArgs;
pValue = ...
0
votes
1
answer
49
views
How to Link an additional c .lib file when making a cython library
I am attempting to make a simple python library that calls LogonUser to see if the plaintext password provided matches the password of the username provided, but when I compile, it gives me this error
...
0
votes
1
answer
18
views
Include <arrayobject.h> header path to compile C python extension in build pipeline using cibuildwheels
I'm developing a python package that contains a C extension. I want to deploy a release for each operating system (linux, windows, macOS) using cibuildwheel. The C extension uses the arrayobject.h ...
0
votes
0
answers
14
views
Import issue when running tests from within a project with cython code
I have a Python library with Cython code.
When I compile the library I manage to import it successfully and use it in other projects. But when I write tests (which are executed from within the library'...
1
vote
0
answers
41
views
not able to embed python tensorflow code in c++
I am building NIST FRVT11 library. I have core code in python, that I want to call from c++, I have followed offical Python C API docs to use python functions in c++.
I am able to load and predict ...
0
votes
1
answer
46
views
Popen() doesn't redirect the stdout to a file [closed]
I have a python program that calls a subprocess using Popen(). This python program is called from a C program, using the Python/C API.
Everything works fine except for the fact that the subprocess ...
1
vote
0
answers
23
views
Why "Python C Extension Types" should have larger .tp_basicsize than their base object to be subclassable with multiple inheritance?
I'm trying to deal with Python C Extensions, reading docs.
And can't understand next statement from here
Note: If you want your type to be subclassable from Python, and your type has the same ...
0
votes
0
answers
49
views
How to determine cause of "RuntimeError: Resource temporarily unavailable" error in Python notebook
In a hosted Python notebook, I'm using the duckdb library and running this code:
duckdb.connect(database=":memory:", read_only=False)
This returns the following error sometimes:
Traceback (...
0
votes
1
answer
38
views
Python C API: What does PyList_Append do on error?
This is not documented in the docs. It just says it "returns 0 for success and -1 for error". What does this mean?
If we're iterating over some data structure (say a linked list/array) and ...
0
votes
0
answers
54
views
python c api with multiple file
While writing python c api, I wanted to separate it into multiple files.
So, I separated the files (module.cpp and support.cpp) and wrote the function declarations in the separate files (support.h).
...
0
votes
0
answers
53
views
Python C API Py_NewInterpreter() freezes thread when creating new sys.stdin
I am building a Python wrapper for a C++ SDK in Python
The app I am building on top of is using a console that is always listening to input on stdin
Everything worked great before I tried to implement ...
0
votes
0
answers
36
views
Cannot find directory for linker -lgomp
I am on an M1 Mac and I have Homebrew GCC installed. I am trying to multithread using OpenMP.
I have a setup.py file containing:
sources = ['pyTsetlinMachineParallel/...
1
vote
1
answer
47
views
PyObject_CallObject crashed when called out of main function scope
I'm building a simple module to wrap a C function. The main function of this module (test_wrapper) basically receives a python function and call it:
#include <Python.h>
static PyObject* ...
0
votes
1
answer
151
views
OpenMP linker -lgomp library not found on M1 mac
My issue is with the openmp not working with a C Extension in a python setup.py file.
I am running this code and I have a setup.py file as below:
from setuptools import *
libTM = Extension('libTM',
...
0
votes
1
answer
72
views
Can't run Python file in C
I have a problem with python api in c. I am trying to run a python script with PyRun_SimpleFile but it fails
I get this error: d:/gcc/bin/../lib/gcc/x86_64-w64-mingw32/11.1.0/../../../../x86_64-w64-...
0
votes
0
answers
42
views
Wrong sequence of bytes after creating of a new code object
I'm trying to use PyCode_New() method of Python 3.10 C API.
I have a problem with the last argument of PyCode_New(). According to the description here: https://docs.python.org/3/c-api/code.html#c....
7
votes
2
answers
194
views
Can you safely change a Python object's type in a C extension?
Question
Suppose that I have implemented two Python types using the C extension API and that the types are identical (same data layouts/C struct) with the exception of their names and a few methods. ...
0
votes
1
answer
55
views
PyPy C API compatibility issues
I'm trying to port an existing extension for cPython to PyPy. It is written using C API. I've got some question which are connected with the compatibility:
The extension uses opcodes from cPython's ...
0
votes
0
answers
44
views
How do I create a Callable from an instance of std::function?
I have a C++ function that returns an instance of std::function. I want to create Python bindings for this function, using only CPython code. So, I want to return this std::function object as a ...
-1
votes
1
answer
61
views
is there pybind11 method that has similar properties of PyString_AsString
I am trying to convert the c++ project from boost to pybind11
QString r = QString(PyString_AsString(result));"
QString r = QString(py::str(result));
-1
votes
1
answer
59
views
PyObject_CallMethod: call static member function from c++
I've embedded Python (3.6) code into my C++ application successfully. I use the Python/C API to call methods from this library. An overview of the python module is as follows:
class MyClass(object):
...
1
vote
0
answers
71
views
Python C API segmentation fault when launching python soft twice
I'm trying to run a python code from a C code twice but I get a segfault the second time.
Here is my c code:
//prgm.c
#include <stdio.h>
#include "Python.h"
int main(void) {
int i;...
2
votes
1
answer
485
views
How to call a python function from C++ with pybind11?
Please consider the following C++ pybind11 program:
#include <pybind11/embed.h>
namespace py = pybind11;
int main() {
py::scoped_interpreter guard{};
py::dict locals;
py::exec(R&...
1
vote
1
answer
74
views
Cibuildwheel Fails to Compile With Static Libraries
I have a Python C extension module which relies on static libraries. Below is my file tree, I haven't included all the files because I am trying to simplify the problem.
folder/
├── src/
| ├── main....
0
votes
0
answers
112
views
python C API error: undefined reference to PyErr_Occurred
I'm working on a Python 2.7 project and I'm attempting to write a c++ extension to speed up our implementation of the D* lite algorithm. Never played with python C API, I'm struggling a lot in setting ...
2
votes
2
answers
117
views
How to Access Current File Path in Python C Extension
In Python, you can get the current file path with the __file__ attribute.
print(__file__)
How can I access this attribute from a Python C Extension? I tried the following code, but the attribute ...
0
votes
0
answers
33
views
Undefined reference to PyAST_mod2obj
So i'm doing some stuff with python c api. I'm trying to parse a string with function PyParser_ASTFromString
There is no error here, I then tried to change mod_ty i got to PyObject* with functiin ...
0
votes
0
answers
90
views
PyGILState_STATE didn't change after PyGILState_Ensure()/PyGILState_Release()
I have a shared library written in C and called in Python.
In a pthread, some Python C API called between PyGILState_Ensure() and PyGILState_Release().
The value of PyGILState_STATE remains the same ...
0
votes
0
answers
63
views
VMCI socket raises an Inappropriate ioctl for device error when using setblocking
I am writing a python 3 extension to support VMCI sockets.
I modified the existing python socket module to support vmci. When doing the same exact workflow using python 2.7, the function setblocking ...
-1
votes
1
answer
96
views
Develop a C module for applying selection sort
I am trying to develop a C module for applying a selection sort algorithm to a list of data and returning the sorted list back to the Python program as a Python list format.
However, I found that the ...
0
votes
1
answer
88
views
Operate on Numpy array from C extension without memory copy
I'm new to C extensions for NumPy and I'm wondering if the following workflow is possible.
Pre-allocate an array in NumPy
Pass this array to a C extension
Modify array data in-place in C
Use the ...
1
vote
1
answer
166
views
How to write a python string to a C struct's (char *) member in python?
I have a C struct passed from C to python, and I want to change the content of a (char *)member in python.
little.c
#include <Python.h>
typedef struct little littleStruct;
struct little{
...
0
votes
1
answer
47
views
How can I create a C module with a "static" object of a custom type?
Let's say I want to write a module called countries that contains information about the countries of the world. I want to write it in C. It will expose a member called countries which is a list of ...
0
votes
1
answer
134
views
How to build a class in C++ to use in Python?
PyMethodDef from Python.h allows to specify Cpp-built functions to use in Python. However, there is much doubt if this can be applied for Cpp-built classes and I can't find anything like PyClassDef ...
2
votes
1
answer
278
views
How to pass a python dictionary to a c function?
I want to call a c function in python code, and pass in a python dictionary as an argument.
little.c
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
PyObject *changeDict(...
2
votes
0
answers
240
views
Link error - cannot build Python C extension in Windows
I need to build a c extension for Python for Windows using distutils. My setup.py looks like this:
My machine is: Windows Server 2019 64 bit.
Python 3.9
(I need to include mysql and a couple of other ...
0
votes
1
answer
132
views
How to acquire GIL for the new thread state created using embed python in C++ application
I have a C++ application where we provide a python editor(which uses python 3.7), users can input and execute the python code in the editor. Following is the sample code where we are creating a new ...
1
vote
0
answers
60
views
Is it safe to call `Py_DecRef` on an object created before the last Py_Initialize?
Assuming all participating modules correctly handle Py_Finalize, does C API allow this:
Py_Initialize();
...
PyObject* myObj = PyObject_Call(simple_class, empty_tuple, NULL);
Py_Finalize();
...
...
0
votes
1
answer
86
views
What's the performance of PyImport_ImportModule(), and what are the best practices for using it?
I have an inner loop C function which (in my case) constructs a Python datetime object:
PyObject* my_inner_loop_fn(void* some_data) {
PyObject* datetime = PyImport_ImportModule("datetime"...
0
votes
0
answers
51
views
PyImport_Import returns ImportError when called from NASM but not from C
I call PyImport_Import to import the NLTK library. When called from NASM as shown below it returns a null pointer and throws an ImportError, but when called from C as shown below it returns a valid ...
4
votes
1
answer
263
views
How to pip install a package from a read-only directory?
I am trying to install a Python (C-extension, if it matters) package that is located in a mounted directory, which for security reasons is read-only. However, by default pip will build the package in ...
0
votes
0
answers
19
views
Py_XDECREF tuple of 1 item causing a crash on exit from function [duplicate]
I am working on a project that calls Python code from C++. In order to call a Python function from C++ I need to prepare input parameters for it. Documentation says that I need to pass a tuple of ...
0
votes
0
answers
41
views
Compiling Python C extension on Linux for Windows (Cross-compilation)
The problem
Hi,
I have a Python C extension that I compile and run on Linux (WSL2) and works well, but now I want to compile it for Windows as well (cross-compilation, i.e. compile on my WSL2 for ...
0
votes
1
answer
357
views
My Python program crashes with "Fatal Python error: deallocating None". What does this error mean?
I've been trying to track down an issue with some Python code compiled from C++ (using swig).
The following information was retrieved by executing gdb using python3-dbg (python version 3.8).
Python ...
1
vote
1
answer
106
views
Are "in place" Cython functions possible?
Suppose I have the C function which returns void
void mysub_wrapper(int *a, int *b)
{
*b = *a + 1;
}
Can I make a wrapper with Cython which passes a and b by reference:
cdef extern void ...
1
vote
1
answer
79
views
Cython module property
In Cython, you can define getter and setter functions for class properties:
cdef class module
property a:
def __get__(self):
cdef int a
get_a(&a)
return a
def __set__(...
1
vote
1
answer
87
views
Implementing decorators in a Python C/C++ extension that can wrap/decorate functions in Python
Python decorators are a very "pythonic" solution to a lot of problems. Because of this, I'd like to include a pre-defined decorator in my C-extension that can decorate functions that are ...
0
votes
0
answers
61
views
Problems starting subprocess that should use different python environment than its parent process
we have written an application (lets call it pythontest.exe) that comes with its own 'Python Windows embeddable package' (lets call it embedded python, should load the Python DLLs from there as well ...
1
vote
0
answers
33
views
setting environment variable for python c extension
I have a python package that uses a C extension. The C code has preprocessor directives, like
#ifdef FLAG
printf("with FLAG\n");
#else
printf("without FLAG\n");
#endif
In ...