[英]How to automatically execute chunks of C++ code (ideally from python)
我有大約 10k 獨立且相對簡單的.cpp 文件(假設只有一個 30 行 main() 函數)。 我想了解它們每個人如何使用許多不同的輸入集(它們通過cin
獲得)運行。 特別是,我想數千次執行以下過程:
或者,選擇一行並獲取每個聲明變量的所有值對我來說也足夠了。
我正在嘗試在 Python 中對此進行編碼,但我也對其他語言開放。 查看相關問題和通用谷歌搜索,我遇到了 libclang(但似乎主要在編譯時查看抽象語法樹)、gdb(可能符合要求,但不確定具體如何)和 pybind11(似乎主要針對集成一次一個 C++ package 而不是逐行運行)。
在有多種選擇的情況下,我更關心代碼的易用性而不是運行分析時的計算效率。
您將如何處理這項任務?
您應該查看 python 的 ctypes 庫: https://docs.python.org/3.8/library/ctypes.html
您可以將 C++ 代碼編譯為共享的 object(Linux 中的 *.so 文件),
然后使用 ctypes 庫(使用ctypes.LibraryLoader
類)將其加載到 python 中。
I did this in the past and I remember that I needed a small C code that "glues" python and C++ (because you need to convert the C data types that python uses into C++ data types).
C“膠水”文件將如下所示:
#include "myCppHeader.h" // includes prototype for C++ function myCppFunction
extern "C" {
int callThisFromPython(int intFromPythonCode)
{
return myCppFunction(intFromPythonCode);
}
}
從 python 端,您將調用callThisFromPython
function(使用 ctypes 庫)。 而這個 function 將調用你的 C++ function myCppFunction
並將結果返回給 Z2FCZ6EEEB43A49BDD7526 您還可以將結構從 python 傳遞到 C,反之亦然。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.