Fix SWIG 4.4 multi-phase init: replace import_array() with import_array1(-1) (#4846)

Summary:
## Problem

Building faiss with SWIG 4.4.0+ fails to compile the generated wrapper:

```
In function 'int SWIG_mod_exec(PyObject*)':
error: cannot convert 'std::nullptr_t' to 'int' in return
  import_array();
```

SWIG 4.4.0 introduced PEP 489 multi-phase module initialization, where `SWIG_mod_exec` returns `int` instead of `PyObject*`. NumPy's `import_array()` macro expands to `return NULL`, which is a type mismatch.

Fixes https://github.com/facebookresearch/faiss/issues/4845.

## Why not just use `import_array1(-1)`?

`import_array1(-1)` expands to `return -1`. This fixes SWIG 4.4+ but breaks older SWIG versions, which generate `PyInit_()` returning `PyObject*` — and the upstream CI (SWIG 4.0.2) confirmed exactly this failure:

```
In function 'PyObject* PyInit__swigfaiss()':
error: invalid conversion from 'int' to 'PyObject*'
  import_array1(-1);
```

## Fix

Isolate the NumPy import into a helper function that always returns `int`, then return the correct error value from `%init` using a `SWIG_VERSION` preprocessor check:

```diff
+%{
+static int _faiss_init_numpy() {
+    import_array1(-1);
+    return 0;
+}
+%}
+
 %init %{
-    import_array();
+    if (_faiss_init_numpy() < 0) {
+#if SWIG_VERSION >= 0x040400
+        return -1;
+#else
+        return NULL;
+#endif
+    }
     PythonInterruptCallback::reset();
 %}
```

- `_faiss_init_numpy()` always returns `int`, so `import_array1(-1)` inside it compiles cleanly under any SWIG version
- The `%init` block then returns the correct type for its enclosing function: `-1` (int) for SWIG 4.4+ multi-phase init, `NULL` (PyObject*) for older single-phase init

Pull Request resolved: https://github.com/facebookresearch/faiss/pull/4846

Reviewed By: junjieqi

Differential Revision: D94921302

Pulled By: mnorris11

fbshipit-source-id: 8d4fab61ffce76a10ee7b3f00bab87471b48e02a
This commit is contained in:
Kota Yamaguchi
2026-03-02 19:48:33 -08:00
committed by meta-codesync[bot]
parent e56d96aa01
commit 28f79bd98e
+15 -1
View File
@@ -1236,9 +1236,23 @@ struct PythonInterruptCallback: faiss::InterruptCallback {
%}
%{
/* See https://github.com/facebookresearch/faiss/issues/4845 */
static int _faiss_init_numpy() {
import_array1(-1);
return 0;
}
%}
%init %{
/* needed, else crash at runtime */
import_array();
if (_faiss_init_numpy() < 0) {
#if SWIG_VERSION >= 0x040400
return -1;
#else
return NULL;
#endif
}
PythonInterruptCallback::reset();
%}