为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蝴蝶刀刀 2022-12-27 10:10:10
题在使用 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 cmoduleImportError: 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.soB) 在 Ubuntu 20、Python 3.8.2 中:Traceback (most recent call last):  File "./py_program.py", line 5, in <module>    import cmoduleImportError: /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 cmodulecmodule.printvol(3.)setup.py"""To install the module defined in cmodule.cpp."""from distutils.core import setup, Extensionsetup(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;}
查看完整描述

1 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

在中,解决问题setup.py的参数:libraries=['armadillo']Extension()


"""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'],

            libraries=['armadillo'], // this solves the problem

            language='c++')],

      )

神奇的是,没有它,arma::也能正确使用。但不是像arma::arma_rng.


这个解决方案是通用的:其他库也会出现同样的问题。实际上,我使用 GNU 科学图书馆 ( ) 复制了相同的内容(并使其工作libraries=['gsl'])。


查看完整回答
反对 回复 2022-12-27
  • 1 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号