简体   繁体   English

在其他应用程序中嵌入python时,如何在子模块(即scipy.optimize.nnls)中导入或调用函数?

[英]When embedding python in another application how do I import or call a function in a submodule (i.e. scipy.optimize.nnls)?

First I'll restate the question: When embedding Python into a C/C++ application using python docs and other resources. 首先,我将重申一个问题:使用python文档和其他资源将Python嵌入C / C ++应用程序时。 I discovered that you can import a module using 我发现您可以使用导入模块

PyObject *pName = PyUnicode_FromString((char*)"scipy");
PyObject *pModule = PyImport_Import(pName); 

but if I try to import "scipy.optimize" 但是如果我尝试导入“ scipy.optimize”

PyObject *pName = PyUnicode_FromString((char*)"scipy.optimize");
PyObject *pModule = PyImport_Import(pName); 

then the program fails to initialize pModule . 然后程序将无法初始化pModule Again if I try 再一次,如果我尝试

PyObject *pName = PyUnicode_FromString((char*)"scipy");
PyObject *pModule = PyImport_Import(pName); 
pFunc = PyObject_GetAttrString(pModule, (char*)"optimize.nnls");

where I put optimize in the function name the it fails to initialize pFunc . 我在函数名称中放置了optimize地方,它无法初始化pFunc How do I import or call a function in a submodule, ie how do I call the function scipy.optimize.nnls? 如何在子模块中导入或调用函数,即如何调用函数scipy.optimize.nnls?

Next, I'll lay out my code in case it helps: 接下来,我将布置我的代码,以防它有所帮助:

/* Relelvant imports
    #include <Python.h>
    #include <numpy/arrayobject.h> 
*/

void nnls::update(const vec& x, const vec& y)
{
    mat B;
    vecToGslVec(x, gslx);
    generateX(X, gslx);
    A = gslMatToMat(X);
    B = A.transpose();
    long double *c_out;

    Py_Initialize();
    PyObject *pName = PyUnicode_FromString((char*)"scipy"); //Issue Here
    check(pName, "pName not initializes.");

    PyObject *pModule = PyImport_Import(pName);
    check(pModule, "pModule not initializes.");

    PyObject *pFunc, *pArgs, *pResult;
    PyArrayObject *pNpArray;

    npy_intp Adims[2]; Adims[0] = A.rows(); Adims[1] = A.cols();
    npy_intp bdim[1];  bdim[0] = y.size();

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, (char*)"optimize.nnls"); //Issue Here
        check(pFunc, "pFunc not initializes.");

        /*program never advances past this point unless I remove this check, 
        in which case I get a segfault, because pFunc is not initialized.*/

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_Pack(2,
                PyArray_SimpleNewFromData(2, Adims, NPY_FLOAT, B.data()),
                PyArray_SimpleNewFromData(1, bdim , NPY_FLOAT, \
                    const_cast<double*> (y.data()))
            );
            check(pArgs, "pArgs not initializes.");
            pResult = PyObject_CallObject(pFunc, pArgs);
            check(pResult, "pResult not initializes.");
            pNpArray = reinterpret_cast<PyArrayObject*>(pResult);
            log_info("not PyArray cast");
        }
        Py_DECREF(pFunc);
    }
    Py_DECREF(pModule);
    Py_DECREF(pArgs);
    c_out = reinterpret_cast<long double*>(PyArray_DATA(pNpArray));
    for(size_t i=0; i<order; i++){
        gsl_vector_set(gslc, i, c_out[i]);
    }
    if (pResult != NULL) Py_DECREF(pResult); Py_DECREF(pNpArray);
    Py_Finalize();
}

Again, My issue is in the lines 同样,我的问题是

PyObject *pModule = PyImport_Import(pName);

and

pFunc = PyObject_GetAttrString(pModule, (char*)"optimize.nnls");

If I set 如果我设置

pName = PyUnicode_FromString((char*)"scipy.optimize"); 

or 要么

pFunc = PyObject_GetAttrString(pModule, (char*)"optimize.nnls");

the code fails to initialized these variables at these points. 代码在这些点上无法初始化这些变量。

So to reiterate my question one last time how do I import the module scipy.optimize or call the function optimize.nnls in this context? 因此,在上一次重申我的问题时,在这种情况下如何导入模块scipy.optimize或调用函数optimize.nnls Thanks. 谢谢。 I hope it isn't too confusing, if it is let me know and I'll clarify. 我希望它不要太混乱,如果让我知道,我会澄清。

Like the rarely-used built-in __import__ function, when you PyImport_Import the name scipy.optimize , the import system does load the scipy.optimize module, but it returns scipy instead of scipy.optimize . 像很少使用的内置__import__函数一样,当您PyImport_Import命名scipy.optimize ,导入系统会加载scipy.optimize模块,但是它返回scipy而不是scipy.optimize You need to follow the attribute chain down to scipy.optimize.nnls : 您需要遵循属性链,直到scipy.optimize.nnls

PyObject *scipy = PyImport_Import(pName);
PyObject *optimize = PyObject_GetAttrString(scipy, "optimize");
PyObject *nnls = PyObject_GetAttrString(optimize, "nnls");

As always, don't forget to Py_DECREF any references you own when you're done with them. 与往常一样,使用Py_DECREF所有引用后,请不要忘记对其进行Py_DECREF That includes things like pName . 包括pName东西。

First of all, I've never use PyImport_Import() . 首先,我从未使用过PyImport_Import() I've always used PyImport_ImportModule() , which takes a const char * arg instead of a PyObject * . 我一直使用PyImport_ImportModule() ,它使用const char * arg而不是PyObject * That should save some steps in your code. 那应该在代码中节省一些步骤。

PyObject *pModule = PyImport_ImportModule("scipy.optimize");
PyObject *pFunc = PyObject_GetAttrString(pModule, "nnls");

This is how I have done things in code I have written. 这就是我用编写的代码完成工作的方式。 PyImport_ImportModule() handles package hierarchies. PyImport_ImportModule()处理包层次结构。 PyObject_getAttrString() does not know what to do with the dot. PyObject_getAttrString()不知道如何处理该点。

I have never used PyImport_Import() , so I don't know how its behavior might change things. 我从未使用过PyImport_Import() ,所以我不知道它的行为可能会改变什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据权重包含到 Scipy NNLS 函数中? - How to include data weight to Scipy NNLS function? 如何在Python中调用scipy.optimize.fmin_cg(func)的函数 - How to call function for scipy.optimize.fmin_cg(func) in Python 如何包含对Scipy NNLS函数解的约束,使其总和为1 - How to include constraint to Scipy NNLS function solution so that it sums to 1 当我调用另一个函数时如何停止一个函数? 使用 tkinter python - How do I stop a function when I call another? using tkinter python 如何在 python 中的另一个 function 中调用 function? - How do I call function inside another function in python? Maya Python:当在另一个函数中创建对象时,如何在一个函数中调用和编辑该对象的属性? - Maya Python: How do i call on and edit attributes of an object in one function when that object was created in another function? 导入程序包时,如何说服Python从子模块导入类? - How can I convince Python to import a class from a submodule when you import the package? Python/Scipy 是否有 firls() 替代品(即加权最小二乘 FIR 滤波器设计)? - Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)? 如何创建自定义 python 解释器? 即某些模块已经包括在内? - How do I create a custom python interpreter? i.e. with certain modules already included? 如何在python magic编码说明符行中指定扩展的ascii(即range(256))? - how do I specify extended ascii (i.e. range(256)) in the python magic encoding specifier line?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM