简体   繁体   中英

Swift with C struct pointer

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;
};

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

But I get the following error:

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

Can anyone help?

swift file

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

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

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

testc-Bridgin-Header.h

#include "mystruct.h"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM