是否可以从 C/C++ 调用 numba jited 函数?

Jān*_*nis 5 c c++ python numba

我想在 python 中接口 C++ 库,它将函数指针作为参数。我看起来可以在 C 中使用 进行调用PyEval_CallObject,但要进一步进行,我需要正确的签名(输入和输出参数的类型)。是否可以从具有指定签名的python返回回调?

另外我有点担心性能,所以我也查看了numba编译python函数的python项目。如果可以在 C/C++ 中访问它以提高性能,我很感兴趣。

Art*_*oul 4

Numba 的 jited 函数是在内存中编译的,而不是在文件中编译的。该函数具有常规的 Pythonic 接口,它是一个瘦包装器,可将 Python 参数转换为 C 类型,并作为常规 C/汇编器函数调用jited 机器代码。

Numba 动态按需编译 (jits) 函数,这意味着它会在第一次调用时进行编译。此外,Numba 还预编译具有不同参数类型的函数,即,如果您传递一种类型,Numba 会编译机器代码的一个实例,如果您传递另一种类型作为参数,Numba 会编译另一个实例。编译的代码被缓存,第二次调用时相同类型的参数使用机器代码的缓存版本。

Numba 的函数是常规的 Python 函数。但 Numba 对ctypes库非常友好,因此它支持转换为 ctypes' CFUNCTYPE,这允许使用给定的固定 C 类型参数直接访问机器代码。

为了仅指定一种类型的参数,您必须编写类似的内容

@numba.njit(numba.int64(numba.int64, numba.int64))
Run Code Online (Sandbox Code Playgroud)

即传递固定类型的参数给@njit装饰器。

顺便说一句,你可以使用@jit(优化程度较低,但可以接受几乎任何Python代码),或者@njit(优化程度更高,但需要严格的代码编写规则)。

下面我为您创建了 C++ 代码示例,它从 C++ 调用 Numba 的 jited 函数。我展示了如何以三种方式调用它 - 1) 使用ctypes包装器作为 C 函数。2) 使用PyObject_Call()作为 Python 函数。3)通过@numba.cfunc装饰器和属性,请在此处.address阅读(@max9111 建议的第三条)。

如果您在只有 C 类型时需要速度和最小的 CALL 开销@cfunc,那么请选择 的解决方案,根据 @max9111 的说法,它是最有效(最快)的解决方案(也是最短实现的)。基本上,.address属性只是给出 C 函数的机器代码的直接地址,无需任何开销和准备。如果您有pyfuncPython 对象作为参数和/或您想要传递不同 Python 类型的对象和/或如果您有@jit(不是@njit ) 和/或您不关心速度,

重要的提示!!!我的代码不会清理任何内容,您应该通过Py_XDECREF()删除所有创建的对所有对象的引用。另外,我可能没有进行所有错误检查,您必须对每个可能返回错误的 Python C API 函数进行错误检查。我做了这两次简化,以使代码更短、更易于理解,只是为了展示示例的要点。

在线尝试一下!

#include <stdexcept>
#include <string>
#include <iostream>
#include <cstdint>

#include <Python.h>

#define ASSERT(cond) { if (!(cond)) throw std::runtime_error( \
    "Assertion (" #cond ") failed at line " + std::to_string(__LINE__) + "!"); }
#define CH(cond) [&]{ auto r = (cond); if (PyErr_Occurred()) { PyErr_Print(); std::cerr << std::flush; \
    throw std::runtime_error("PyAssertion (" #cond ") failed at line " + std::to_string(__LINE__) + "!"); } return r; }()

int main() {
    try {
        std::cout << "Wait..." << std::endl;
        Py_Initialize();
        auto globals = CH(PyDict_New()), locals = CH(PyDict_New());
        CH(PyRun_String(R"(
import numba as nb, ctypes

@nb.njit(nb.int64(nb.int64, nb.int64))
def mul1(a, b):
    return a * b

@nb.cfunc(nb.int64(nb.int64, nb.int64))
def mul2(a, b):
    return a * b

cmul1 = ctypes.CFUNCTYPE(
    ctypes.c_int64, ctypes.c_int64, ctypes.c_int64)(mul1)
addr1 = ctypes.cast(cmul1, ctypes.c_void_p).value
addr2 = mul2.address
        )", Py_file_input, globals, locals));
        //std::cout << CH(PyUnicode_AsUTF8AndSize(CH(PyObject_Str(locals)), nullptr)) << std::endl;
        auto cfunc1 = (int64_t (*)(int64_t, int64_t))
            CH(PyLong_AsUnsignedLongLong(CH(PyDict_GetItemString(locals, "addr1"))));
        auto cfunc2 = (int64_t (*)(int64_t, int64_t))
            CH(PyLong_AsUnsignedLongLong(CH(PyDict_GetItemString(locals, "addr2"))));
        std::cout << "pyfunc: 3 * 5 = " << CH(PyUnicode_AsUTF8AndSize(
            CH(PyObject_Str(CH(PyObject_Call(
                CH(PyDict_GetItemString(locals, "mul1")), PyTuple_Pack(
                    2, PyLong_FromLongLong(3), PyLong_FromLongLong(5)), nullptr /* named args */
            )))), nullptr)) << std::endl << std::flush;
        std::cout << "cfunc1 (0x" << std::hex << uint64_t(cfunc1) << std::dec
            << "): 3 * 5 = " << cfunc1(3, 5) << std::endl << std::flush;
        std::cout << "cfunc2 (0x" << std::hex << uint64_t(cfunc2) << std::dec
            << "): 3 * 5 = " << cfunc2(3, 5) << std::endl << std::flush;
        ASSERT(Py_FinalizeEx() == 0);
        return 0;
    } catch (std::exception const & ex) {
        std::cerr << "Exception: " << ex.what() << std::endl << std::flush;
        return -1;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Wait...
pyfunc: 3 * 5 = 15
cfunc1 (0x7f5db072f080): 3 * 5 = 15
cfunc2 (0x7f5db05b2010): 3 * 5 = 15
Run Code Online (Sandbox Code Playgroud)