question folks: if I need to define a KN function ...
# kotlin-native
i
question folks: if I need to define a KN function that will be called on Objective-C that returns a string and it has this signature
override fun foo(): CPointer<ByteVar>?
, should I use
StableRef
like:
Copy code
override fun foo(): CPointer<ByteVar>? {
        return StableRef
            .create(name.encodeToByteArray())
            .asCPointer()
            .rawValue
            .let { interpretCPointer(it) }
    }
d
⚠️ No! ⚠️
Or rather, I don't think that does what you think it does.
If you want to return a
CPointer<ByteVar>
, you're gonna have to allocate memory and return it.
How long do you need this string for? What's the scope of it?
Do you basically just want to
malloc
?
You can also just do this and let the caller decide.
Copy code
override fun foo(): CValues<ByteVar>? {
    return name.encodeToByteArray().cstr
}
o
@ivan.savytskyi why do you need that? why not return Kotlin's string and rely upon interop conversions?
i
The issues that this function is defined by the Objective-C protocol, I would love to return just string but c interop tool generated this signature
@kotlinx.cinterop.ObjCMethod public abstract fun foo(): kotlinx.cinterop.CPointer<kotlinx.cinterop.ByteVar
The issue is that I don't really know what is the scope of this string should be, as this function is supposed to be called sometime later by external C library, that I don't have control
this is the declaration in the header file:
Copy code
@protocol XXX <NSObject>
....
@property (nonatomic, readonly) const char *foo;`
I was thinking of
return name.cstr.getPointer(Arena())
but I'm not sure if this is correct usage as well
d
All you need to decide is when/where you want to free the allocated memory.