2

I have a C-header file (let's call it myheader.h) that contains some character string definitions such as:

#define MYSTRING "mystring-constant"

In Cython, I create a cmy.pxd file that contains:

cdef extern from "myheader.h":
    cdef const char* MYSTRING "MYSTRING"

and a corresponding my.pyx file that contains some class definitions, all headed by:

from cmy cimport *

I then try to reference that string in a Python script:

from my import *

def main():
     print("CONSTANT ", MYSTRING)

if __name__ == '__main__':
    main()

Problem is that I keep getting an error:

NameError: name 'MYSTRING' is not defined

I've searched the documentation and can't identify the problem. Any suggestions would be welcomed - I confess it is likely something truly silly.

ralph
  • 141
  • 7
  • For functions you to have use something like `cpdef` to make them visible from Python. – hpaulj Jul 11 '18 at 21:46
  • Possible duplicate of [Import non-integer constant in .pyx file](https://stackoverflow.com/questions/36624179/import-non-integer-constant-in-pyx-file) – DavidW Jul 11 '18 at 21:57
  • [This](https://stackoverflow.com/questions/31766219/export-constants-from-header-with-cython) is also related but not quite what you're after – DavidW Jul 11 '18 at 21:57

1 Answers1

3

You cannot access cdef-variables from Python. So you have to create a Python object which would correspond to your define, something like this (it uses Cython>=0.28-feature verbatim-C-code, so you need a recent Cython version to run the snippet):

%%cython
cdef extern from *:   
    """
    #define MYSTRING "mystring-constant"
    """
    # avoid name clash with Python-variable
    # in cdef-code the value can be accessed as MYSTRING_DEFINE
    cdef const char* MYSTRING_DEFINE "MYSTRING"

#python variable, can be accessed from Python
#the data is copied from MYSTRING_DEFINE   
MYSTRING = MYSTRING_DEFINE 

and now MYSTRING is a bytes-object:

>>> print(MYSTRING)
b'mystring-constant'
ead
  • 32,758
  • 6
  • 90
  • 153
  • This is a great solution, thanks! I wonder if there is a way to reference a variable with the *same* name in the cdef-code and in the python code? That would be usefull for debugging cythonized .py code. – werner Mar 04 '21 at 18:07