0

I have a C function in a file with name (Buffer is a C struct)

 BufferInit(Buffer *buffer, int32_t size)

As I am moving to Swift, in my Swift class I declare a private var like

 var buffer:Buffer?

and in init function I make a call like this

 BufferInit(&buffer, 32)

But I get compilation errors, what is the correct way to achieve the same in Swift? I call call the same BufferInit from Objective-C without issues but Swift is messy.

EDIT: Here are details,

 typedef struct {
 void *buffer;
 int32_t length;
 int32_t tail;
 int32_t head;
 } Buffer;

Error is compiler is asking me to unwrap buffer and correct the code as(which I don't think is correct):

 BufferInit(&buffer!, 32)
asked Apr 27, 2017 at 17:58
3
  • Can you add the exact text of the errors you're getting, and the details of the Buffer struct? Commented Apr 27, 2017 at 18:02
  • My guess: buffer should be initialized and not an optional. Commented Apr 27, 2017 at 18:05
  • It should be initialized to something, like all values 0? Commented Apr 27, 2017 at 18:06

1 Answer 1

1

Your C function is imported to Swift as

func BufferInit(_ buffer: UnsafeMutablePointer<Buffer>!, _ size: Int32)

and you have to pass the address of a (initialized, nonoptional) variable of type Buffer as an inout expression. Structures imported from C have a default constructor in Swift which initializes all members to zero, so you can write

var buffer = Buffer()
BufferInit(&buffer, 32)
answered Apr 27, 2017 at 18:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.