ralph
ralph

Reputation: 151

Referencing Cython constants in Python

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.

Upvotes: 2

Views: 2350

Answers (1)

ead
ead

Reputation: 34326

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'

Upvotes: 3

Related Questions