加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift – 使用Objective-C包装器调用C文件 – 传递Int值

发布时间:2020-12-14 04:37:39 所属栏目:百科 来源:网络整理
导读:我正在玩 Swift项目调用c方法.我使用 this教程来设置和获取字符串值,完美地工作. 然后我尝试用整数值做同样的事情,我在objective-c包装器类中遇到了一些问题. #import Foundation/Foundation.h#import "TestCppClassWrapper.h"#include "TestCppClass.h"@int
我正在玩 Swift项目调用c方法.我使用 this教程来设置和获取字符串值,完美地工作.

然后我尝试用整数值做同样的事情,我在objective-c包装器类中遇到了一些问题.

#import <Foundation/Foundation.h>
#import "TestCppClassWrapper.h"
#include "TestCppClass.h"
@interface TestCppClassWrapper()
@property TestCppClass *cppItem;
@end
@implementation TestCppClassWrapper
- (instancetype)initWithTitle:(NSString*)title: (NSInteger*)variable
{
    if (self = [super init]) {
        self.cppItem = new TestCppClass(std::string([title cStringUsingEncoding:NSUTF8StringEncoding]),std::uintptr_t(variable));
    }
    return self;
}
- (NSString*)getTitle
{
    return [NSString stringWithUTF8String:self.cppItem->getTtile().c_str()];
}
- (void)setTitle:(NSString*)title
{
    self.cppItem->setTitle(std::string([title cStringUsingEncoding:NSUTF8StringEncoding]));
}
- (NSInteger*)getVariable
{
    return [NSInteger self.cppItem->getVariable()];
}
- (void)setVariable:(NSInteger*)variable
{
    self.cppItem->setVariable(std::NSInteger(variable));
}
@end

你可能已经猜到了,这里出现了问题

enter image description here

我既不熟悉obj-c也不熟悉c,这就是为什么我无法弄清楚我究竟应该如何处理类型,字符串是个别情况(编码和东西),所以我很难理解它到Int.

#include "TestCppClass.h"
TestCppClass::TestCppClass() {}
TestCppClass::TestCppClass(const std::string &title,const std::int8_t &variable): m_title(title),m_variable(variable) {}
TestCppClass::~TestCppClass() {}
void TestCppClass::setTitle(const std::string &title)
{
    m_title = title;
}
void TestCppClass::setVariable(const std::int8_t &variable)

{
    m_variable = variable * 2;
}
const std::string &TestCppClass::getTtile()
{
    return m_title;
}
const std::int8_t &TestCppClass::getVariable()
{
    return m_variable;
}

提前致谢

解决方法

NSInteger不是一个类,它是一个longde的typedef,所以只需按原样使用它.

你可以做到

- (instancetype)initWithTitle:(NSString*)title: (NSInteger)variable
{
    if (self = [super init]) {
        self.cppItem = new TestCppClass(std::string([title cStringUsingEncoding:NSUTF8StringEncoding]),variable);
    }
    return self;
}

- (NSInteger) getVariable
{
    return self.cppItem->getVariable();
}
- (void)setVariable:(NSInteger)variable
{
    self.cppItem->setVariable(variable);
}

但是你会在setter中获得一个缩小的转换.
(我不确定这是一个问题,还是NSInteger对你的Swift界面至关重要.)

并且通过引用传递std :: int8_t是没有意义的 – 只需使用它“plain”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读