Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 如何访问C属性?_Objective C_Frameworks_Swift - Fatal编程技术网

Objective c 如何访问C属性?

Objective c 如何访问C属性?,objective-c,frameworks,swift,Objective C,Frameworks,Swift,我在swift代码中使用libxml2框架,不确定访问属性的正确语法是什么 在Objective-C中,您可以通过以下方式访问该属性: currentNode->name 但当尝试对Swift使用相同的语法时,我发现以下错误: “大括号语句块是未使用的闭包” 我猜这是因为“->”已经被预订了 我也试过: currentNode.name 但我得到了一个错误: “'xmlNodePtr'没有名为'name'的成员” 可以在Swift中访问C属性吗?方法是使用UnsafePointer类型

我在swift代码中使用libxml2框架,不确定访问属性的正确语法是什么

在Objective-C中,您可以通过以下方式访问该属性:

currentNode->name
但当尝试对Swift使用相同的语法时,我发现以下错误:

“大括号语句块是未使用的闭包”

我猜这是因为“->”已经被预订了

我也试过:

currentNode.name
但我得到了一个错误:

“'xmlNodePtr'没有名为'name'的成员”


可以在Swift中访问C属性吗?

方法是使用
UnsafePointer
类型的
memory
变量

但是,为了加快速度,我首选的方法是定义一个自定义运算符来取消对
UnsafePointer
类型的引用:

operator postfix & { }

@postfix func &<T>(lhs: UnsafePointer<T>) -> T {
    return lhs.memory;
}
运算符后缀&{}
@后缀func&(lhs:UnsafePointer)->T{
返回lhs.memory;
}
完成此操作后,您可以执行以下操作:

let doc = xmlReadDoc(nil, "my-url", "UTF-8", 0);
let root = xmlDocGetRootElement(doc);

var currentChild = root&.children;
while (currentChild != nil) {
    var str = String.fromCString(UnsafePointer<CChar>(currentChild&.name));
    println("Child name: \(str)");

    currentChild = currentChild&.next;
}
let doc=xmlReadDoc(nil,“我的url”,“UTF-8”,0);
设root=xmlDocGetRootElement(doc);
var currentChild=根和.children;
while(currentChild!=nil){
var str=String.fromCString(UnsafePointer(currentChild&.name));
println(“子名称:\(str)”;
currentChild=currentChild&next;
}

如果您想允许链接,甚至可以将结果返回为null。

澄清解释:这些不是真正的属性,至少不是ObjC@property意义上的属性。
->
是指针解引用和结构成员访问的组合。因此,实际上您已经有了指向结构的指针,并且需要取消引用该指针(以获取结构本身),然后访问您感兴趣的结构的成员。(我自己也不知道用Swift怎么做。)谢谢你的解释。有趣的解决方案。注意,您不必使用
UnsafePointer
,尤其是如果您正在围绕一个窗口构建自己的桥接例程,在这个窗口中您可能能够保证指针的安全-请参阅标准库中的
CMutablePointer
和friends。@rickster这是正确的,尽管OP特别提到了lxml2,所以这就是我的答案。