带有C结构指针的Swift [英] Swift with C struct pointer

查看:88
本文介绍了带有C结构指针的Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含指针的C结构,所有指针都定义在C头文件中:

I have a C struct that contains a pointer, all defined in a C header:

struct testA {
  int iSignal;
  struct testB *test;
};

struct testB {
  int iPro;
};

然后我有一个Swift程序来初始化此struct的实例:

Then I have a Swift program to initialize an instance of this struct:

var a = testA()
var b = testB()
a.test = &b // this line error

但是出现以下错误:

'&' used with non-inout argument of type 'UnsafeMutablePointer<testB>'

任何人都可以帮忙吗?

推荐答案

交换文件

import Foundation

var s = testA()
s.iSignal = 1
s.test = UnsafeMutablePointer<testB>.alloc(1)  // alocate memory for one instance of testB
s.test.memory.iPro = 10

// if your testB is allocated in you C code, than just access it
let testB = UnsafeMutablePointer<testB>(s.test)
dump(testB.memory)

/*
▿ __C.testB
    - iPro: 10
*/

dump(s)

/*
▿ __C.testA
    - iSignal: 1
    ▿ test: UnsafeMutablePointer(0x1007009C0)
        - pointerValue: 4302309824

*/

dump(s.test.memory)

/*
▿ __C.testB
    - iPro: 10
*/

s.test.dealloc(1) // dont forget deallocate s.test underlying memory ! 

mystruct.h

mystruct.h

#ifndef mystruct_h
#define mystruct_h
struct testA {
    int iSignal;
    struct testB *test;
};

struct testB {
    int iPro;
};
#endif /* mystruct_h */

testc-Bridgin-Header.h

testc-Bridgin-Header.h

#include "mystruct.h"

这篇关于带有C结构指针的Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆