简体   繁体   中英

Encoding/decoding C Struct with components that are not encodable

I have a struct defined in a C header like:

struct ComputeParameters {
    float scale;
    vector_float4 rgba;
}

It has to be defined in C and not in Swift for a reason, so I can't just add add the Coding protocol to it.

I need to be able store and restore the contents of instances of the struct - ideally from Swift, but I can make an Objective-C class to code it if necessary.

I tried to encode it with Obj-c:

NSValue *structValue = [NSValue value:&computeParams withObjCType:@encode(struct ComputeParameters)];

But I get this error:

Encoding of 'struct ComputeParameters' type is incomplete because 'vector_float4' (aka 'simd_float4') component has unknown encoding

Other than encoding each and every component of the struct (there are like 3 dozen components), is there a better way?

You can access the actual bytes of the struct and then convert those bytes to NSData but that ends up being very low level and machine dependent. This is the one extreme of your options and may work and work well as long as you have the same underlying machine architecture. Then you can just as well code up the whole implementation in C and not use NSData/NSCoding at all.

If you use NSCoding then it comes with its own set of limitations as you see and you need to work with what it gives you. There are a few handy low level functions such as encodeInt64 but then you still end up working with the individual members of the struct. This is the other extreme where you encode the individual struct members for each struct.

If you use Objective-C the middle ground can be to create a class for each struct along with code to get a struct from the class and to init a class from a struct. Then you need code to encode / decode each class. This will probably be a lot of work but if this integrates well into your solution I think is the better / more maintainable option.

The most direct way forward would be to use the low level NSCoding functions but you still end up mapping each and every struct member to some low level function but at least without a class to facilitate the encoding. Then you can eg create an identifier for each struct and use that when you decode to know what struct you need to create and decode into.

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