本文介绍了将 Scipy 嵌入 C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题,但它让我难住了.

This is a very basic question, but it has me stumped.

我正在尝试将一些 scipy 例程嵌入到 c 程序中.但是,我无法成功完成导入任何 scipy 模块的初始步骤.

I am trying to embed some scipy routines into a c-program. However, I am unable to successfully complete the initial step of importing any scipy modules.

我可以导入scipy的顶层,没有得到null返回值,所以我很确定安装没有问题......

I can import the top-level of scipy, without getting a null return value, so I'm pretty sure the install is not a problem...

PyObject *pckg_name, *pckg;

pckg_name = PyString_FromString("scipy");
pckg = PyImport_Import(pckg_name);
if (!pckg)
{
        printf("Error importing python module %s.\n");
        return;
} 

...但我无法达到任何更低的水平.我已经尝试了 PyImport_Import 和 PyImport_ImportModule 的各种组合,例如导入scipy.stats"作为第 1 步,或在导入 scipy 后将 stats 作为第 2 步导入,但没有任何效果.

...but I am unable to get to any lower level. I've tried all kinds of combinations with PyImport_Import and PyImport_ImportModule, e.g. importing "scipy.stats" as step 1, or importing stats as step 2 after importing scipy, but nothing is working.

我能够从random"模块导入和使用函数,所以我认为我的基本 Python 安装没有问题.我知道我在这里遗漏了一些明显的东西,但我无法弄清楚它是什么.

I am able to import and use functions from the "random" module, so I don't think there's a problem with my base Python install. I know I'm missing something obvious here, but I can't figure out what it is.

推荐答案

就其价值而言,这对我有用:

For what it's worth, this works for me:

try_scipy.c

#include <Python.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    PyObject *pckg_name;
    PyObject *pckg;

    Py_Initialize();

    pckg_name = PyString_FromString("scipy.stats");
    pckg = PyImport_Import(pckg_name);
    if (!pckg) {
        printf("fail\n");
    }
    else {
        printf("got it!\n");
        Py_DECREF(pckg);
    }
    Py_DECREF(pckg_name);

    Py_Finalize();

    return EXIT_SUCCESS;
}

编译运行:

$ gcc try_scipy.c `python-config --cflags --ldflags` -o try_scipy
$ ./try_scipy
got it!

这篇关于将 Scipy 嵌入 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:09