dll export function to ctypes

  c++, ctypes, python

Background

I have some functions which are written in C++, which require high real-time performance. I want to quickly export these functions as dynamic link library to be exposed to Python so that I could do some high level programming.

In these functions, in order to simply usage, I use PyList_New in <Python.h> to collect some intermedia data. But I met some errors.

Code Example

I found the core problem is that I CAN’T event export a python object. After compiling the source to dll and use ctypes to load it, result shows

OSError: exception: access violation reading 0x0000000000000008

C++ code:

#include <Python.h>


#ifdef _MSC_VER
#define DLL_EXPORT  __declspec( dllexport )
#else
#define DLL_EXPORT
#endif

#ifdef __cplusplus
extern "C"{
#endif

DLL_EXPORT PyObject *test3() {
    PyObject* ptr = PyList_New(10);
    return ptr;
}

#ifdef __cplusplus
}
#endif

Python test code:


if __name__ == "__main__":
    import ctypes

    lib = ctypes.cdll.LoadLibrary(LIB_DLL)
    
    test3 = lib.test3
    test3.argtypes = None
    test3.restype = ctypes.py_object
    
    print(test3())

Environment Config

Clion with Microsoft Visual Studio 2019 Community, and the arch is amd64.

I know that, the right way is to use the recommanded method to wrap C++ source using Python/C Api to a module, but it seems that I have to code a lot. Anyone can help?

Source: Windows Questions C++

LEAVE A COMMENT