gpt4 book ai didi

python - 直接从 C 调用 mpmath

转载 作者:行者123 更新时间:2023-11-30 19:37:34 25 4
gpt4 key购买 nike

我想从 C 代码访问 mpmath 的特殊函数。我知道如何通过中间 python 脚本来做到这一点。例如,为了计算超几何函数,C 程序:

#include <Python.h>

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);
}

通过调用 GGauss_2F1.py 脚本可以正常工作:

from mpmath import *
def Gauss_2F1(a1, a2, b1, z):
hpg= hyp2f1(a1, a2, b1, z)
return hpg

有没有办法直接从 C 调用 mpmath 函数 hyp2f1,而无需借助中间的 python 脚本?我猜测mpmath模块可以通过命令导入

PyRun_SimpleString("from mpmath import *");   

但是我如何访问实际的函数呢?

最佳答案

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

好的。按照您的建议:

#include <Python.h>

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);
}

代码似乎按预期工作并且正在生成正确的结果。感谢您的“耐心”...

关于python - 直接从 C 调用 mpmath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39645580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com