Python/C++:可以导入 Armadillo (arma::) 但不能导入子程序

在使用 Armadillo 的 C++ 中创建 Python 扩展时,出现以下错误:


A) 在 Mac OS Mojave 10.14.4、Python 3.7.5 中:


Traceback (most recent call last):

  File "./py_program.py", line 5, in <module>

    import cmodule

ImportError: dlopen(/Users/angel/.pyenv/versions/3.7.5/lib/python3.7/site-packages/cmodule.cpython-37m-darwin.so, 2): Symbol not found: __ZTWN4arma23arma_rng_cxx11_instanceE

  Referenced from: /Users/angel/.pyenv/versions/3.7.5/lib/python3.7/site-packages/cmodule.cpython-37m-darwin.so

  Expected in: flat namespace in /Users/angel/.pyenv/versions/3.7.5/lib/python3.7/site-packages/cmodule.cpython-37m-darwin.so

B) 在 Ubuntu 20、Python 3.8.2 中:


Traceback (most recent call last):

  File "./py_program.py", line 5, in <module>

    import cmodule

ImportError: /usr/local/lib/python3.8/dist-packages/cmodule.cpython-38-x86_64-linux-gnu.so: undefined symbol: _ZN4arma23arma_rng_cxx11_instanceE

它们都是由于使用arma::arma_rng::randn<double>(),见下文。


我该如何解决?


细节

我想py_program.py导入在cmodule.cpp. 按照文档https://docs.python.org/3/extending/extending.html,我有文件py_program.py,setup.py和cmodule.cpp. 它们的内容是:


py_program.py

#!/usr/bin/env python3


"""Import and use cmodule."""


import cmodule

cmodule.printvol(3.)

setup.py

"""To install the module defined in cmodule.cpp."""

from distutils.core import setup, Extension

setup(name='cmodule', version='1.0',  \

      ext_modules=[

          Extension(

            'cmodule', ['cmodule.cpp'],

            extra_compile_args=['-std=c++11'],

            language='c++')],

      )

cmodule.cpp

/* Module to be used in Python.

   All Python stuff follows Sec. 1.8 of 

   https://docs.python.org/3/extending/extending.html */

#define PY_SSIZE_T_CLEAN

#include <Python.h>

#include <armadillo>



double f()

// Fails at using Armadillo.

// The module works if I delete this function.

{

    double rn_y = arma::arma_rng::randn<double>();

    return rn_y;

}



arma::cx_double g()

// Succeeds at using Armadillo.

{

    arma::cx_double value(0., 1.);

    return value;

}



蝴蝶刀刀
浏览 132回答 1
1回答

喵喵时光机

在中,解决问题setup.py的参数:libraries=['armadillo']Extension()"""To install the module defined in cmodule.cpp."""from distutils.core import setup, Extensionsetup(name='cmodule', version='1.0',&nbsp; \&nbsp; &nbsp; &nbsp; ext_modules=[&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Extension(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'cmodule', ['cmodule.cpp'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; extra_compile_args=['-std=c++11'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; libraries=['armadillo'], // this solves the problem&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; language='c++')],&nbsp; &nbsp; &nbsp; )神奇的是,没有它,arma::也能正确使用。但不是像arma::arma_rng.这个解决方案是通用的:其他库也会出现同样的问题。实际上,我使用 GNU 科学图书馆 ( ) 复制了相同的内容(并使其工作libraries=['gsl'])。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python