How can I argue from Python C code?

I am writing a Python class in C and I want to put statements in my debugging code. assert.h suits me. This is only added to the debug compilation, so there is no chance that an assert failure will not affect the user of the Python * code.

I am trying to separate my "library" code (which should be separate for Python-related code), so I can use it from another C code. My Python methods are, therefore, thin wrappers around my pure-C code.

Therefore, I cannot do this in my "library" code:

 if (black == white) { PyErr_SetString(PyExc_RuntimeError, "Remap failed"); } 

because it pollutes my pure-C code using Python. It is also much uglier than simple

 assert(black != white); 

I believe that the Distutils compiler always installs NDEBUG , which means that I cannot use assert.h even in debug builds.

Mac OS and Linux.

Help!

* one argument that I heard against a statement in C code called from Python.

+5
source share
3 answers

Just use assert.h . It is a myth that distutils always defines NDEBUG ; it does this only for Microsoft msvc on Windows, and then only when called from the Python release build (not from the Python debug build).

To then define NDEBUG in your own releases, pass the -D command-line option to setup.py build_ext.

Change Apparently, NDEBUG is defined by default using the Python Makefile OPT parameter. To do this, reset

 OPT="-g -O3" python setup.py build 
+7
source

Create your own macro, for example myassert() for different situations. Or create a macro that checks the global variable to see if the macro is used from Python code or โ€œnormalโ€ C. The Python module entry point would have to set this variable to true or you could use function pointers, one for Python code , another default for code C.

+2
source

Define the NDEBUG macro in setup.py :

 ext_modules = [Extension( ... undef_macros=['NDEBUG'], )] 

This will result in a command line like

 gcc ... -DNDEBUG ... -UNDEBUG ... 

Which (albeit ugly) does the right thing, that is, supports statements.

+2
source

Source: https://habr.com/ru/post/970979/


All Articles