Massa7ca
Massa7ca

Reputation: 11

Exception: access violation reading when calling a C function from Python

I wanted to play around a bit with the Python C Api. But ran into an error.

OSError: exception: access violation writing 0x0000000000000020

The error occurs on the lines PyObject_RichCompare(first, second, Py_LT)

There are no errors in the first and second variables. If you remove the line PyObject_RichCompare(first, second, Py_LT) everything works.

Tried building "DLL" both on Linux in GCC and on Windows in Visual Studio. Everywhere I get this error

C code

#include "Python.h"

extern "C" {
    __declspec(dllexport)
    long test(PyObject* list) {
        PyObject* first, * second;
        int t = PyList_Size(list);
        first = PyList_GetItem(list, 0);
        second = PyList_GetItem(list, 1);
        PyObject* result = PyObject_RichCompare(first, second, Py_LT);
        return PyLong_AsLong(first) + PyLong_AsLong(second);
    }
}

And Python Code

import ctypes

lib = ctypes.CDLL('please.dll')
lib.test.restype = ctypes.c_long
lib.test.argtypes = [ctypes.py_object]

py_values = [1, 645, 546, 8646, 45646, 6545688, 5465]
a = lib.test(py_values)

print(a)

Upvotes: 1

Views: 1146

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177406

The GIL must be held to use Python C APIs. Use PyDLL for that:

lib = ctypes.PyDLL('please.dll')

Upvotes: 2

Related Questions