Cython avoid PyObject and object convertion

37 views
Skip to first unread message

Feiyang

unread,
May 21, 2024, 3:57:06 PMMay 21
to cython-users
Hi, thanks in advance for any help!

I have a cython function defined like below
cdef double foo(str arg1, double arg2) nogil:
    if arg1 == "bar":
        return 1.0
    else:
        return 0.0
In another function, I need to apply this function to a a structured object. Currently, the structured c object is and the other function is defined as follows:
cdef struct fooArgs:
    PyObject* arg1
    double arg2

cdef double wrapped_foo(fooArgs* args) nogil:
    return foo(args.arg1, args.arg2)
I use a PyObject pointer because a str cannot be part of a c struct. but when I try to compile this, I get error "Cannot convert PyObject * to python object."

However, I can see in the generated C code
static double __pyx_f_4test_foo(PyObject *__pyx_v_arg1, CYTHON_UNUSED double __pyx_v_arg2) {
  double __pyx_r;
  int __pyx_t_1;
  int __pyx_lineno = 0;
  const char *__pyx_filename = NULL;
  int __pyx_clineno = 0;
  #ifdef WITH_THREAD
  PyGILState_STATE __pyx_gilstate_save;
  #endif
that a PyObject * is being used to represent arg1.

How should I tweak the signature of fooArgs or implementation of wrapped_foo, so that wrapped_foo can take a c struct as an argument, and use foo on the content of the struct?



Reply all
Reply to author
Forward
0 new messages