C-API 注册一个针对内置 ufunc 的 ufunc 循环

C-API register a ufunc loop against builtin ufunc

我正在寻找构建一个 numpy 扩展模块,它声明一个新的结构化数据类型并提供必要的内部 ufunc 循环以允许在其上执行 built-in math operations

按照 creating your own ufunc 上的指南,我已经能够:

当作为模块导出时,这会按预期工作,但需要用户通过导出的 ufunc 包调用该函数(即 my_package.add_uncertain);我宁愿通过 numpy.add.

获得此实现

numpy C-API 文档的 registering a ufunc loop section 中使用的语言似乎表明我应该能够针对内置 ufunc 注册 ufunc 循环。为此,我相信我应该将内置 PyUFuncGenericFunction 传递给 PyUFunc_RegisterLoopForDescr.

如果我知道我是否在正确的轨道上,我将非常感激,如果是的话,我应该在哪里寻找内置 PyUFuncGenericFunction

the numpy rational type test 中包含的解决方案是使用 PyImport_Import 导入 numpy,然后使用 PyObject_GetAttrString 获取 add ufunc,此时可以注册新的内部循环:

  numpy_str = PyUnicode_FromString("numpy");
  if (!numpy_str) 
      return NULL;
  numpy = PyImport_Import(numpy_str);
  Py_DECREF(numpy_str);
  if (!numpy)
      return NULL;

  PyUFuncObject *add_ufunc = PyObject_GetAttrString(numpy, "add");
  if (!add_ufunc)
      return NULL;

  PyUFunc_RegisterLoopForDescr(
      add_ufunc,
      uncertain_double_dtype,
      &add_uncertain_double,
      add_uncertain_double_dtypes,
      NULL);