Calling mpmath directly from C
<p>I want to access mpmath's special functions from a C code.
I know how to do it via an intermediate python script.
For instance, in order to evaluate the hypergeometric function, the C program:</p>

<pre><code>#include &lt;Python.h&gt;

void main (int argc, char *argv[])
{
   int npars= 4;
   double a1, a2, b1, x, res;
   PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
   PyObject *pa1, *pa2, *pb1, *px;

   a1= atof(argv[1]);
   a2= atof(argv[2]);
   b1= atof(argv[3]);
   x= atof(argv[4]);

   setenv("PYTHONPATH", ".", 1); // Set PYTHONPATH TO bin directory
   Py_Initialize();

   pa1= PyFloat_FromDouble(a1);
   pa2= PyFloat_FromDouble(a2);
   pb1= PyFloat_FromDouble(b1);
   px=  PyFloat_FromDouble(x);
   pName = PyString_FromString("GGauss_2F1");
   pModule = PyImport_Import(pName);
   pFunc = PyObject_GetAttrString(pModule, "Gauss_2F1");
   pArgs = PyTuple_Pack(npars, pa1, pa2, pb1, px);
   pValue = PyObject_CallObject(pFunc, pArgs);

   res= PyFloat_AsDouble(pValue);
   printf("2F1(x)= %.15f\n", res);
}
</code></pre>

<p>works all right by calling the GGauss_2F1.py script:</p>

<pre><code>from mpmath import *
def Gauss_2F1(a1, a2, b1, z):
   hpg= hyp2f1(a1, a2, b1, z)
   return hpg
</code></pre>

<p>Is there a way to call the mpmath function hyp2f1 directly from C, without having to resort to an intermediate python script?
I guess that the mpmath module can be imported by the command </p>

<pre><code>PyRun_SimpleString("from mpmath import *");   
</code></pre>

<p>But how do I access the actual function?</p>

<blockquote>
  <p>What? No! Literally do the things you did to access
  GGauss_2F1.Gauss_2F1, just with the names changed. Why are you trying
  to PyRun_SimpleString("from mpmath import *")? â user2357112</p>
</blockquote>

<p>Ok.  Following your suggestions:</p>

<pre><code>#include &lt;Python.h&gt;

void main (int argc, char *argv[])
{
   int npars= 4;
   double a1, a2, b1, x, res;
   PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
   PyObject *pa1, *pa2, *pb1, *px;

   a1= atof(argv[1]);
   a2= atof(argv[2]);
   b1= atof(argv[3]);
   x= atof(argv[4]);

   setenv("PYTHONPATH", ".", 1); // Set PYTHONPATH TO bin directory
   Py_Initialize();

   pa1= PyFloat_FromDouble(a1);
   pa2= PyFloat_FromDouble(a2);
   pb1= PyFloat_FromDouble(b1);
   px=  PyFloat_FromDouble(x);
   pName = PyString_FromString("mpmath");
   pModule = PyImport_Import(pName);
   pFunc = PyObject_GetAttrString(pModule, "hyp2f1");
   pArgs = PyTuple_Pack(npars, pa1, pa2, pb1, px);
   pValue = PyObject_CallObject(pFunc, pArgs);

   res= PyFloat_AsDouble(pValue);
   printf("2F1(x)= %.15f\n", res);
}
</code></pre>

<p>The code seems to work as expected and is generating the correct result.
Thank you for your "patience"...</p>

python c mpmath