You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SWIG封装C函数时传递NumPy数组遇TypeError问题求助

SWIG 4.3封装C函数时NumPy数组参数类型错误排查

C函数定义

void AesAutoWhiteBalance_Balance(
    const unsigned short* measurementsR,
    const unsigned short* measurementsG,
    const unsigned short* measurementsB,
    const unsigned measureCount,
    const unsigned bitWidth,
    float* outR, float* outG, float* outB);

SWIG接口文件

%module AesAutoWhiteBalance

%{
#define SWIG_FILE_WITH_INIT
#include "AesAutoWhiteBalance.h"
%}
// Include the NumPy typemaps
%include "numpy.i"

%init %{
import_array();
%}

// Wrap the AesAutoWhiteBalance_Balance function
%apply (unsigned short* IN_ARRAY1, unsigned int DIM1) { 
(const unsigned short* measurementsR, const unsigned measureCount), 
(const unsigned short* measurementsG, const unsigned measureCount), 
(const unsigned short* measurementsB, const unsigned measureCount) };

%include "../include/AesAutoWhiteBalance.h"

Python测试代码

# Open the image
img = Image.open(image_path)
# Convert the image to RGB mode (if not already in RGB mode)
img = img.convert('RGB')

# Convert the image into a numpy array
img_array = np.array(img).astype(np.uint16)

# Define the identity matrix (Unity matrix)
identity_matrix = np.eye(3).astype(np.float32)

arrayLength = img.height * img.width

red = img_array[:, :, 0].flatten()
green = img_array[:, :, 1].flatten()
blue = img_array[:, :, 2].flatten()

AesAutoWhiteBalance_Balance(
    red,
    green, 
    blue,
    arrayLength,
    8,
    identity_matrix[0][0],
    identity_matrix[1][1],
    identity_matrix[2][2]
)

错误信息

TypeError: in method 'AesAutoWhiteBalance_Balance', argument 1 of type 'unsigned short const *'

编译安装过程正常,但传递uint16类型的NumPy数组时仍触发上述类型错误,以下是排查思路:

  • 检查NumPy数组内存连续性:SWIG的numpy.i typemap对非连续内存数组可能无法正确识别,用red.is_contiguous()验证,若数组非连续,调用red = red.copy()生成连续数组后再传递。
  • 修正SWIG typemap的const匹配:原%apply中使用的unsigned short*与C函数的const unsigned short*类型不匹配,调整为(const unsigned short* IN_ARRAY1, unsigned int DIM1)后重新生成包装代码。
  • 显式声明数组类型typemap:在SWIG接口中使用numpy.i提供的宏显式指定类型,比如:
    %numpy_typemap(IN_ARRAY1, const unsigned short*, unsigned int)
    
  • 修复输出参数传递方式:C函数的float* outR/outG/outB是输出指针,当前Python传递的是标量值,类型不匹配。需改为传递可写的NumPy数组,或在SWIG中为输出参数添加对应的OUTPUT类型typemap。
  • 检查SWIG生成的包装代码:查看自动生成的C包装文件,确认参数解析逻辑是否正确处理了NumPy数组到const unsigned short*的转换,是否存在类型检查逻辑误判。

内容的提问来源于stack exchange,提问作者Philli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 03:27:28