次のようなことをしたいと思います。
- C++からPythonを呼び出したい。
- pythonが終わったらC++に値を返す。(importでエラーが発生しない場合、pythonからの返り値は4)
c++ファイルをコンパイルして実行ファイルを実行します。
実行すると、pythonファイルにエラーが出ます。
原因はpythonファイルで行われているimport文のエラーです。
pythonファイルでnumpyをインポートすると、エラーが出ます。
ちなみに、OSとsysがインポートできることを確認しました。
pythonのパスは間違っているからなのでしょうか?
Pythonのパスには気をつけたつもりでしたが、どうなんでしょう...
ご教授いただけると幸いです。
本投稿は次のように構成にしました
- ◆コード
- ◆エラーの説明
- ◆環境情報
- ◆コードを動かすために
-ディレクトリの作成
-作成されたpython環境
-コンパイル
コード
◆main.cpp
#include <Python.h> #include <iostream> #include <stdio.h> #include <string> using namespace std; int main() { Py_Initialize(); PyObject *pName = NULL; PyObject *pModule = NULL; PyObject *pTmp = NULL; PyObject *pFunc = NULL; char *sTmp; int data; const char *pythonFileName = "python_code_sample"; // The extension (.py) must be removed. const char *functionName = "sample_test"; // This function must be included in the script. PyObject *sys = PyImport_ImportModule("sys"); PyObject *path = PyObject_GetAttrString(sys, "path"); PyList_Append(path, PyUnicode_FromString(".")); PyObject *pythonName = PyUnicode_FromString(pythonFileName); PyObject *pythonModule = PyImport_Import(pythonName); Py_DECREF(pythonName); if (pythonName == NULL) { cout << "pName is empty!!!" << endl; } if (pythonModule == NULL) { cout << "pModule is empty!!!" << endl; } if (pythonModule != NULL) { cout << __LINE__ << endl; pFunc = PyObject_GetAttrString(pythonModule, functionName); pTmp = PyObject_CallObject(pFunc, NULL); PyArg_Parse(pTmp, "i", &data); printf("%d\n", data); } Py_Finalize(); return 0; }
◆python_code_sample.py
import numpy as np #import random print("hoge1") def sample_test(): a = [1,2,3,4,5] print("hige_1") #b = random.choice(a) print("hoge_2") return a[3] #return b if __name__ == "__main__": print(sample_test())
エラーの説明
◆Numpyをimportした時、下記のエラー内容が出ます。
/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/bin /Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/site-packages/numpy/__init__.py:140: UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package, see http://github.com/IntelPython/mkl-service from . import _distributor_init pModule is empty!!! Traceback (most recent call last): File "/Users/username/git/python_c_api_sample/python_code_sample.py", line 10, in <module> import numpy as np File "/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/site-packages/numpy/__init__.py", line 142, in <module> from . import core File "/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/site-packages/numpy/core/__init__.py", line 50, in <module> raise ImportError(msg) ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.8 from "/Users/username/git/python_c_api_sample/./a.out" * The NumPy version is: "1.18.5" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: dlopen(/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/site-packages/numpy/core/_multiarray_umath.cpython-38-darwin.so, 2): Symbol not found: _PyBaseObject_Type Referenced from: /Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/site-packages/numpy/core/_multiarray_umath.cpython-38-darwin.so Expected in: flat namespace in /Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/site-packages/numpy/core/_multiarray_umath.cpython-38-darwin.so
◆randomをimportした時、下記のエラー内容が出ます。(pythonファイルの2行目を修正してください)
File "./python_code_sample.py", line 2, in <module> import random File "/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/random.py", line 41, in <module> from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil ImportError: dlopen(/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/lib-dynload/math.cpython-38-darwin.so, 2): Symbol not found: _PyExc_MemoryError Referenced from: /Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/lib-dynload/math.cpython-38-darwin.so Expected in: flat namespace in /Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/lib-dynload/math.cpython-38-darwin.so
◆環境情報
I installed anaconda in pyenv.
I created the environment as follows.
- Anaconda installer is anaconda3-5.0.1
- python3.8.1
- macOS(Catalina version:10.15.4)
- output is g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1 Apple clang version 11.0.3 (clang-1103.0.32.59) Target: x86_64-apple-darwin19.4.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
◆コードを動かすために
ディレクトリの作成
mkdir sample_test_python_c_api && cd sample_test_python_c_api There are two files in the directory: main.cpp and python_code_sample.py.
作成されたpython環境
pyenv local anaconda3-5.0.1
conda create -n your_env_name python=3.8 anaconda
pyenv local anaconda3-5.0.1/envs/your_env_name
export PYTHONHOME=/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name export PYTHONPATH=$PYTHONHOME/bin
cコンパイル
g++ -fPIC main.cpp $(python3.8-config --cflags --ldflags) -lpython3.8 python3.8-config --cflags -I/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/include/python3.8 -I/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/include/python3.8 -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/include -arch x86_64 -I/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/include -arch x86_64 python3.8-config --ldflags -L/Users/username/.pyenv/versions/anaconda3-5.0.1/envs/your_env_name/lib/python3.8/config-3.8-darwin -ldl -framework CoreFoundation
回答1件
あなたの回答
tips
プレビュー