How to use a C function with complex types in Python?

后端 未结 2 424
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 07:57

I decided to port some of my Python functions to C, mostly following this simple tutorial. Problem is that my C function returns a complex float, and there\'s no correspondi

相关标签:
2条回答
  • 2021-01-15 08:24

    Create a small C wrapper function:

    void integrand_wrapper(float *re, float *im, double r, double z)
    {
        float _Complex  result;
        float _Complex  theta = (*re) + I*(*im);
        result = integrand(theta, r, z);
        (*re) = creal(result);
        (*im) = cimag(result);
    }
    

    The re and im pointers hold the real and imaginary parts of theta when called, and the real and imaginary parts of the result afterwards.

    In your Python code, call integrand_wrapper() using e.g.

    def integrand(theta, r, z):
        global _integr
        theta = complex(theta)
        re = c_float(theta.real)
        im = c_float(theta.imag)
        _integr.integrand_wrapper(byref(re), byref(im), c_double(r), c_double(z))
        return complex(float(re), float(im))
    

    Note that if integrand() is defined in a binary library you cannot modify, you can always create another dynamic library containing only integrand_wrapper, that is dynamically linked (in C) to the original binary library.

    Overall, I don't think the added overhead is significant at all. It is certainly worth testing.

    0 讨论(0)
  • 2021-01-15 08:38

    Naively, perhaps split it into two arguments, Re(z), Im(z) If that's not an option, perhaps pass the argument to the python function complex().

    These are naive solutions; perhaps they don't work but if you haven't considered it and in lack of better responses, may be worth experimenting with.

    Good luck!

    0 讨论(0)
提交回复
热议问题