How to pass vectors from python to c++ dll compiled in debug with cython


I'm new on cython and I need to wrap a C++ dll with python. I'm getting stuck when trying to pass vector from python to C++ and then back to python when compiling c++ dll in debug mode. Here below is the simple code I have.

I'm using visual studio version 16.5.4 to compile the C code; the name of the dll it generates is dummyLib. I have python 3.7. I'm compiling cython from pycharm 2019.2 terminal with the command: python build_ext --inplace

If I compile the dll in debug mode, then when executing the python script, it crashes with 0xC0000005: access violation error. If I put traces at the beginning of the C use_vector() function, they are not printed.

If I compile the dll in release mode, change Debug to Release in and in the script, then python script executes without crashing and I can have traces out.

My question is what do I need to do to make it work in debug?

Thanks a lot for your help!

file my_module.h

extern "C" __declspec(dllexport) void use_vector( std::vector<int> & v );

file my_module.cpp

__declspec(dllexport) void use_vector( std::vector<int>& v )
    v.resize( 3 );
    v[0] = 2;
    v[1] = 3;
    v[2] = 4;  

from setuptools import Extension, setup
from Cython.Build import cythonize
from Cython.Distutils import build_ext
import os

root_ml = os.path.abspath(os.path.join(__file__, os.pardir, "..", "..", "..", ".."))

extensions = [Extension("check_lib",
              extra_compile_args=["-std=c++11", "-O3", "-Wall", "-I" + root_ml + r"/cpp/Dummy/DummyLib/inc"],
              extra_link_args=[root_ml + r"/cpp/Dummy/DummyLib/x64/Debug/DummyLib.lib"],
              include_dirs=[root_ml + r"/cpp/Dummy/DummyLib/inc"],
              library_dirs=[root_ml + r"/cpp/Dummy/DummyLib/x64/Debug"],

    name='Cython wrapper app',
    cmdclass={'build_ext': build_ext},


cimport cython
from libcpp.vector cimport vector

cdef extern from "my_module.h":

    cpdef void use_vector(vector[int]& v) ;


cimport cdummyCython
cimport cython
from libcpp.vector cimport vector
ctypedef vector[int] int_vec

cpdef cpp_simple_vector():
    cdef   int_vec v
    return v

import os
import sys

ROOT_PATH = os.path.abspath(os.path.join(__file__, os.pardir))
DUMMY_LIB_PATH = os.path.abspath(os.path.join(ROOT_PATH, "..", "..", "..", "..",
                                        "cpp", "Dummy", "DummyLib", "x64", "Debug"))
DUMMY_CYTHON_PATH = os.path.abspath(os.path.join(ROOT_PATH, "..", ))

os.environ["PATH"] += os.pathsep + DUMMY_CYTHON_PATH
os.environ["PATH"] += os.pathsep + DUMMY_LIB_PATH

import check_lib as cython_wrapper 

def main():
    vect = [4, 5, 6, 8]

if __name__ == "__main__":
    print("Dummy caller", main())
asked on Stack Overflow Jun 22, 2020 by Rose

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0