下面是一个最小的例子(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.i
和pyfragments.swg
包含到项目中 - 我试过
%apply
等等。
但是什么都不管用!
请问最小限度的事情是什么?
1条答案
按热度按时间balp4ylt1#
type(nparr[0])
是numpy.int32
,而SWIG需要Python的int
类型,因此可以使用printMyInt(int(nparr[0]))
将数组元素转换为SWIG能够理解的Python类型。此外,虽然我找不到它的文档,但我在检查生成的代码时发现,定义
SWIG_PYTHON_CAST_MODE
将添加一个将参数强制转换为int
的尝试,所以下面也可以工作:使用方法: