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

使用pyobjc调用OC接口时报depythonifying 'char', got 'str'错误如何解决

问题解决方法

报错根因

你传入的data是Python的str类型,而Objective-C接口要求的uint8_t*是无符号字节指针类型,pyobjc无法直接将字符串转换为对应C指针类型,因此抛出类型转换错误。

解决步骤

1. 优先使用bytes类型传参

对于硬编码的二进制内容,直接给字符串加b前缀转换为bytes类型即可,列表形式的字节值可以通过bytes()方法转换:

import objc

senddata = Device.alloc().initWithCommunicationInterface_(tcpInterface)
command = 'ABCw'
args = 0x00
# 改为实际发送字节长度,避免硬件读取越界
writelength = 2
readlength = 0x100
# 字符串加b前缀转为bytes类型
data = b'\x50\x40'
# 列表形式字节的转换方式:
# data = bytes([0x50, 0x40, 0x00, 0xFF])
timeout = 500
# 最后一位error参数传objc.nil,匹配NSError**类型要求
success, error = senddata.executeabcCommand_withArgs_withData_writeLength_readLength_timeoutMilliseconds_error_(command, args, data, writelength, readlength, timeout, objc.nil)

2. 复杂场景用ctypes创建可写缓冲区

如果需要发送可变长度内容、或者需要读取接口返回的data数据,用ctypes构造可写的字节缓冲区更稳妥:

import objc
import ctypes

senddata = Device.alloc().initWithCommunicationInterface_(tcpInterface)
command = 'ABCw'
args = 0x00
writelength = 2
readlength = 0x100
# 创建256字节的无符号字节缓冲区
data_buf = (ctypes.c_uint8 * 256)()
# 填充待发送数据
data_buf[0] = 0x50
data_buf[1] = 0x40
timeout = 500

success, error = senddata.executeabcCommand_withArgs_withData_writeLength_readLength_timeoutMilliseconds_error_(command, args, data_buf, writelength, readlength, timeout, objc.nil)

# 调用完成后如果需要读返回数据,直接读取缓冲区内容即可
# return_data = bytes(data_buf[:readlength])

注意事项

  • writelength参数需要和实际发送的字节长度一致,避免硬件侧读取越界
  • 若需要接口写入返回数据到data指针,必须使用可写的ctypes缓冲区,不能传入只读的bytes类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:06:00