2

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?

0

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

withUnsafeMutablePointer(&b) { (b) -> Void in a.test = b.memory }
Then I get error: Cannot convert value of type 'inout testB' to expected argument type 'inout _'
@Cindy check my updated answer. you can see which direction you have to move. the whole project is three files, ....aloc(1) alocate memory for testB structure. you are responsible to free the memory!!! (see s.test.dealloc(1))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.