SWIG:将numpy数组的项转换为C++ typedef

f8rj6qna  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(152)

下面是一个最小的例子(ubuntu 18.04,swig 4.2.0):

Var.hpp

#include <iostream>

typedef int MY_INT;

void printMyInt(MY_INT v)
{
  std::cout << "MyInt is " << v << std::endl;
}

var.i

%module pyvar

%include Var.hpp

%{
  #include "Var.hpp"
%}

test_var.py

#!/usr/bin/python3

from pyvar import *
import numpy as np

v = 6
arr = [v]
nparr = np.array(arr)

printMyInt(v)         # OK
printMyInt(arr[0])    # OK
printMyInt(nparr[0])  # NOK

最后一条指令将产生以下错误消息:

Traceback (most recent call last):
  File "/home/fors/Projets/test/swig/cpp_python_npint64/test_var.py", line 12, in <module>
    printMyInt(nparr[0])  # NOK
  File "/home/fors/Projets/test/swig/cpp_python_npint64/pyvar.py", line 63, in printMyInt
    return _pyvar.printMyInt(v)
TypeError: in method 'printMyInt', argument 1 of type 'MY_INT'

以下内容:https://numpy.org/doc/stable/reference/swig.interface-file.html

  • 我尝试将numpy.ipyfragments.swg包含到项目中
  • 我试过%apply等等。

但是什么都不管用!
请问最小限度的事情是什么?

balp4ylt

balp4ylt1#

type(nparr[0])numpy.int32,而SWIG需要Python的int类型,因此可以使用printMyInt(int(nparr[0]))将数组元素转换为SWIG能够理解的Python类型。
此外,虽然我找不到它的文档,但我在检查生成的代码时发现,定义SWIG_PYTHON_CAST_MODE将添加一个将参数强制转换为int的尝试,所以下面也可以工作:

%module test

%inline %{
#define SWIG_PYTHON_CAST_MODE
#include <iostream>

typedef int MY_INT;

void printMyInt(MY_INT v)
{
  std::cout << "MyInt is " << v << std::endl;
}
%}

使用方法:

>>> from test import *
>>> import numpy as np
>>> a=np.array([6])
>>> printMyInt(a[0])
MyInt is 6

相关问题