CFSwapInt16LittleToHost

CFSwapInt16LittleToHost

我正在将代码从Objective-C转换为Swift,并且在转换时遇到问题,特别是字节操作。特别是,我得到了一个错误“Can not invoke CFSwapInt16LittleToHost with a argument list of(Int16)”。目标C代码为:

@interface THSampleDataFilter ()
@property (nonatomic, strong) NSData *sampleData;
@end

@implementation THSampleDataFilter

- (id)initWithData:(NSData *)sampleData {
self = [super init];
if (self) {
    _sampleData = sampleData;
}
return self;
}
- (NSArray *)filteredSamplesForSize:(CGSize)size {

    NSMutableArray *filteredSamples = [[NSMutableArray alloc] init];
    NSUInteger sampleCount = self.sampleData.length / sizeof(SInt16);
    NSUInteger binSize = sampleCount / size.width;

    SInt16 *bytes = (SInt16 *) self.sampleData.bytes;

    SInt16 maxSample = 0;

    for (NSUInteger i = 0; i < sampleCount; i += binSize) {

    SInt16 sampleBin[binSize];

    for (NSUInteger j = 0; j < binSize; j++) {
        sampleBin[j] = CFSwapInt16LittleToHost(bytes[i + j]);
    }

    SInt16 value = [self maxValueInArray:sampleBin ofSize:binSize];
    [filteredSamples addObject:@(value)];

    if (value > maxSample) {
        maxSample = value;
    }
}

我的Swift代码是:
class THSampleDataFilter : NSObject
{
    var sampleData: NSData?

    init(sampleData: NSData)
{
   super.init()
   self.sampleData = sampleData
}

func filteredSamplesForSize(size: CGSize) -> NSArray?
{
    var filteredSamples = NSMutableArray()
    var sampleCount:UInt = UInt(Int(self.sampleData!.length) / Int(sizeof(Int16)))
    var binSize = UInt(sampleCount / UInt(size.width))

    var bytes: UnsafePointer<Int16> = UnsafePointer<Int16>(self.sampleData!.bytes)
    var maxSample: Int16 = 0

    for var i:UInt = 0; i < sampleCount; i = i + binSize
        {
            var sampleBin: [Int16] = []

            for var j: UInt = 0; j < binSize; j++
            {
                sampleBin.append(CFSwapInt16LittleToHost(bytes[i + j]))
            }

            let value: Int16 = self.maxValueInArray(sampleBin, size: binSize)
            filteredSamples.addObject(NSNumber(short: value))

            if value > maxSample
            {
                maxSample = value
            }
        }

问题是:
sampleBin.append(CFSwapInt16LittleToHost(bytes[i + j]))

当我得到错误“Cannotinvoke CFSwapInt16LittleToHost with a argument list of(Int16)”时。我试过所有我能想到的组合。
任何帮助都将不胜感激!
谢谢你找我。

最佳答案

CFSwapInt16LittleToHost需要一个UInt16,而不是一个Int16

sampleBin.append(CFSwapInt16LittleToHost(UInt16(bytes[i + j])))

或将bytes改为UInt16指针。
var bytes: UnsafePointer<UInt16> = UnsafePointer<UInt16>(self.sampleData!.bytes)

关于objective-c - 无法在Swift中将参数正确传递给CFSwapInt16LittleToHost,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32430567/

10-11 00:47