需要使用C++调用Python代码,但是总提示numpy错误,输出信息如下:
- Traceback (most recent call last):
- File "C:\Python\Python36\lib\site-packages\numpy\core\__init__.py", line 16, in <module>
- from . import multiarray
- ImportError: cannot import name 'multiarray'
-
- During handling of the above exception, another exception occurred:
-
- Traceback (most recent call last):
- File "<string>", line 1, in <module>
- File "C:\Python\Python36\lib\site-packages\numpy\__init__.py", line 142, in <module>
- from . import add_newdocs
- File "C:\Python\Python36\lib\site-packages\numpy\add_newdocs.py", line 13, in <module>
- from numpy.lib import add_newdoc
- File "C:\Python\Python36\lib\site-packages\numpy\lib\__init__.py", line 8, in <module>
- from .type_check import *
- File "C:\Python\Python36\lib\site-packages\numpy\lib\type_check.py", line 11, in <module>
- import numpy.core.numeric as _nx
- File "C:\Python\Python36\lib\site-packages\numpy\core\__init__.py", line 24, in <module>
- raise ImportError(msg)
- ImportError:
- Importing the multiarray numpy extension module failed. Most
- likely you are trying to import a failed build of numpy.
- If you're working with a numpy git repo, try `git clean -xdf` (removes all
- files not under version control). Otherwise reinstall numpy.
-
C++代码很简单:
- #include <iostream>
- #include "./python/36.8/include/Python.h"
-
- int main()
- {
- wchar_t home[] = L"C:/Python/Python36";
- Py_SetPythonHome(home);
- Py_Initialize();
- int r = Py_IsInitialized();
-
- if (r == 0)
- {
- std::cout << "初始化Python环境失败" << std::endl;
- Py_Finalize();
- return -1;
- }
-
- PyRun_SimpleString("import sys");
- PyRun_SimpleString("sys.path.append('C:/Python/Python36/Lib/site-packages')");
- PyRun_SimpleString("import numpy");
- PyObject* model = 0;// PyImport_ImportModule("algorithm2");
-
- if (model == nullptr)
- {
- std::cout << "加载Python文件失败" << std::endl;
- PyErr_Print();
- Py_Finalize();
- return -1;
- }
-
- PyObject* dict = PyModule_GetDict(model);
-
- if (dict == nullptr)
- {
- Py_DECREF(model);
- std::cout << "获取符号字典失败" << std::endl;
- Py_Finalize();
- return -1;
- }
-
- PyObject* ptr = PyDict_GetItemString(dict, "load_model");
- //Py_DECREF(dict);
-
- if (ptr == nullptr)
- {
- Py_DECREF(model);
- std::cout << "获取load_model失败" << std::endl;
- Py_Finalize();
- return -1;
- }
-
- //Py_DECREF(ptr);
- Py_DECREF(model);
- Py_Finalize();
-
- return 0;
- }
-
-