我目前正在上課,我被要求在 Python 和 C 之間建立集成,因為我們將在后面的課程中使用這兩者。我的講師提供了一些簡單的 C 和 Python 代碼,以便我們測驗集成,還提供了有關如何使用 Visual Studio 進行設定的說明。我目前只能訪問 Ubuntu,而我的(非常舊的)筆記本電腦將無法處理 VM。
我目前使用 Clion 作為我的 IDE,使用 Anaconda 作為虛擬環境。我花了一天的大部分時間試圖解決這個問題,我相信這個問題與我的 CMake 檔案有關,因為我現在對 CMake 幾乎一無所知,但計劃盡快學習它。
CMakeLists.txt、main.cpp 和 myPython.py 都在主專案目錄中。
CMakeLists.txt
cmake_minimum_required(VERSION 3.21)
project(myProject)
set(CMAKE_CXX_STANDARD 14)
add_executable(myProject main.cpp)
target_include_directories(myProject PUBLIC /usr/include/python3.9)
target_link_directories(myProject PUBLIC /usr/lib/python3.9)
target_link_libraries(myProject PUBLIC python3.9)
對于 CMakeLists.txt,我還嘗試了以下操作,但無論我使用哪一個,都得到相同的錯誤/輸出
cmake_minimum_required(VERSION 3.21)
project(myProject)
set(CMAKE_CXX_STANDARD 14)
find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
add_executable(myProject main.cpp)
target_link_libraries(myProject PUBLIC Python3::Python)
主檔案
#include <python3.9/Python.h>
#include <iostream>
#include <string>
using namespace std;
// the main in the provided code is void but Clion gave me an error saying to change it to int
int main()
{
cout << "Start 1 \n";
Py_Initialize();
cout << "2\n";
PyObject* my_module = PyImport_ImportModule("myPython");
cerr << my_module << "\n";
PyErr_Print();
cout << "3\n";
PyObject* my_function = PyObject_GetAttrString(my_module,
"printsomething");
cout << "4\n";
PyObject* my_result = PyObject_CallObject(my_function, NULL);
Py_Finalize();
return 0;
}
我的Python.py
import re
import string
def printsomething():
print("Hello from Python!")
預期的輸出是
Start 1
2
01592AE0 // this will vary since it's the .py files location
3
4
Hello from Python!
當我運行它時我得到的是
Start 1
2
0 // output is red
3
ModuleNotFoundError: No module named 'myPython' // output is red
由于我不熟悉 CMake,并且在談到 Ubuntu 時會認為自己是“普通用戶”,所以我可能需要有關所提供的任何步驟的一些額外細節。
uj5u.com熱心網友回復:
之后將其添加到您的主要功能中 Py_Initialize();
PySys_SetPath(L".:/usr/lib/python3.8");
這是 python 模塊的搜索路徑。添加.到當前路徑中搜索。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/413501.html
標籤:
