1

I am working on a C++ project that needs to be wrapped in Cython to ultimately use in integration tests in Python. I have a global variable used to default a value in a function in my C++ header file that looks like

header file
const uint8_t kAudioLevel = 0x5a;

This is used in a function in the c++ files like

void func(uint audioLevel=kAudioLevel)

I am wrapping this function in Cython, and currently have another variable with the same name used in my .pyx file like

DEF kAudioLevel

This default value is passed into the func() wrapper in C++ to allow that value to be defaulted. However, I would really like to have this variable used in the wrapper be imported directly from the header file, so I have a single source of truth and dont have to change this variable twice every time. I have tried adding the following:

pxd file
cdef extern from "header.h":
cdef cppclass Class:
    int kAudioLevel

And then attempt to use kAudioLevel directly in the .pyx like so

def func(audioLevel = kAudioLevel):
return client.func(audioLevel)

This is to allow us to have the value be defaulted across Cython and C++, and not have to edit it twice. However, the variable is not found when I try this. Not sure if I have to add the header class to both the pxd and pyx files and how to do this. I looked over the Cython documentation but didnt find anything useful.

  • Maybe related? https://stackoverflow.com/questions/31766219/export-constants-from-header-with-cython – Lala5th Aug 03 '21 at 19:27

1 Answers1

0

For a const member like cpy.hh:

#ifndef CPY_HH
#define CPY_HH

#include <cstdint>

const uint8_t kAudioLevel = 5;

#endif

with cytest.pyx:

from libc.stdint cimport uint8_t

cdef extern from "cpy.h":
    cdef uint8_t kAudioLevel

Allows me to use kAudioLevel within my .pyx file. With a exposedKAudioLevel = kAudioLevel I can expose this to outside the module.

If you wanted a truly global variable, that is a bit more complicated, but with cpy.hh:

#ifndef CPY_HH
#define CPY_HH

#include <cstdint>

extern uint8_t kAudioLevel;

#endif

cpy.cc:

#include "cpy.hh"

uint8_t kAudioLevel = 5;

and the same cytest.pyx as above, I could create a variable I could access and modify, from both .pyx and .cc.

Unfortunately kAudioLevel is not exposed to the outside importer, so to access/modify, helper functions would be needed, like getVal(), setVal(newVal), as far as I saw.

Lala5th
  • 1,137
  • 7
  • 18