[英]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.