What is the grammar of rule of this code in Objective-C or in C language? - objective-c

I'm reading the code of Mach Ports, I want to know what's the paradigm of a piece of code. I mean I knew the grammar of struct of objective-c, but I don't know what grammar of message.header = (mach_msg_header_t) {......};
The complete code is below.
natural_t data;
mach_port_t port;
struct {
mach_msg_header_t header;
mach_msg_body_t body;
mach_msg_type_descriptor_t type;
} message;
message.header = (mach_msg_header_t) {
.msgh_remote_port = port,
.msgh_local_port = MACH_PORT_NULL,
.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0),
.msgh_size = sizeof(message)
};

The header is assigned to the type-casted mach_msg_header_t pseudo constructor that initializes some of the fields. A break down of the structure is available here : http://web.mit.edu/darwin/src/modules/xnu/osfmk/man/ (partially pasted below)
typedef struct {
mach_msg_bits_t msgh_bits;
mach_msg_size_t msgh_size;
mach_port_t msgh_remote_port;
mach_port_t msgh_local_port;
mach_port_seqno_t msgh_seqno;
mach_msg_id_t msgh_id;
} mach_msg_header_t;
The bit you referenced, does the assignment of the low level fields in the structure and copy into the header.
message.header = (mach_msg_header_t) {
.msgh_remote_port = port,
.msgh_local_port = MACH_PORT_NULL,
.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0),
.msgh_size = sizeof(message)
};

Related

Packed Unions in SystemVerilog

The code is not too long so I am posting the complete code.
// Code your design here
module temp;
typedef enum logic[15:0]
{
ADD = 16'h0000,
SUB = 16'h0001
} my_opcode_t;
typedef enum logic[15:0]
{
REG = 16'h0000,
MEM = 16'h0001
} my_dest_t;
typedef struct packed
{
my_opcode_t opcode; // 16-bit opcode, enumerated type
my_dest_t dest; // 16-bit destination, enumerated type
logic [15:0] opA;
logic [15:0] opB;
} my_opcode_struct_t;
my_opcode_struct_t cmd1;
typedef union packed
{
my_opcode_struct_t opcode_s; //"fields view" to the struct
logic[1:0][31:0] dword; // "dword view" to the struct
} my_opcode_union_t;
my_opcode_union_t cmd2;
initial begin
$display("cmd1 = %p",cmd1);
$display("cmd2 = %p", cmd2);
// Access opcode_s struct fields within the union
cmd2.opcode_s.opcode = ADD;
cmd2.opcode_s.dest = REG;
cmd2.opcode_s.opA = 16'h0001;
cmd2.opcode_s.opB = 16'h0002;
$display("cmd1 = %p",cmd1);
$display("cmd2 = %p", cmd2);
// Access dwords struct fields within the union
cmd2.dword[1] = 32'h0001_0001; // opcode=SUB, dest=MEM
cmd2.dword[0] = 32'h0007_0008; // opA=7, opB=8
$display("cmd2 = %p", cmd2);
end
endmodule
Source: https://www.verilogpro.com/systemverilog-structures-unions-design/
Output:
I ran this code in EDA playground. I did not understand why is it showing"
cmd2='{opcode_s:'{opcode:SUB, dest:MEM, opA:'h7,opB:'h8}}
I was expecting, it would print dword values.
What is it missing in my understanding about unions?
Is it because we are not using cmd2.dword[0] or cmd2.dword[1] it is printing some garbage values?
The reason you do not print dword values is due to the behavior of the %p format specifier. Refer to IEEE Std 1800-2017, section 21.2.1.7 Assignment pattern format:
The %p format specifier may be used to print aggregate expressions
such as unpacked structures, arrays, and unions. ... For unions, only
the first declared elements shall be printed.
If you change your union declaration as follows (with dword first):
typedef union packed
{
logic[1:0][31:0] dword; // "dword view" to the struct
my_opcode_struct_t opcode_s; //"fields view" to the struct
} my_opcode_union_t;
you will see this output:
cmd1 = '{opcode:'hxxxx, dest:'hxxxx, opA:'hxxxx, opB:'hxxxx}
cmd2 = '{dword:'hxxxxxxxxxxxxxxxx}
cmd1 = '{opcode:'hxxxx, dest:'hxxxx, opA:'hxxxx, opB:'hxxxx}
cmd2 = '{dword:'h10002}
cmd2 = '{dword:'h1000100070008}

Swift: Trouble Using Enums Declared in Objective-C, In Swift

OK. Looked at the various answers when I typed out the question, and don't see the answer listed.
This seems such a basic, fundamental issue that I MUST be doing something wrong, but I am being driven crazy (actually, not much of a "drive." More of a short putt) trying to figure out what I am getting wrong.
I have created a test project that can be downloaded here (small project).
In any case, I encountered this, when working on importing a large Objective-C SDK that I wrote into Swift.
Everything works great. Until... I try to do comparisons on enums declared in C.
Obviously, C enums are not turned into Swift enums, but I am having trouble figuring out how to use them.
Here's a sample of what you will see in the test project;
I have a couple of C files that declare enums:
#import <Foundation/Foundation.h>
typedef enum
{
StandardEnumType_Undef = 0xFF,
StandardEnumType_Value0 = 0x00,
StandardEnumType_Value1 = 0x01,
StandardEnumType_Value2 = 0x02
} StandardEnumType;
typedef NS_ENUM ( unsigned char, AppleEnumType )
{
AppleEnumType_Undef = 0xFF,
AppleEnumType_Value0 = 0x00,
AppleEnumType_Value1 = 0x01,
AppleEnumType_Value2 = 0x02
};
StandardEnumType translateIntToEnumValue ( int inIntValue );
int translateEnumValueToInt ( StandardEnumType inValue );
AppleEnumType translateIntToAppleEnumValue ( int inIntValue );
int translateAppleEnumValueToInt ( AppleEnumType inValue );
The functions mentioned do pretty much what it says on the tin. I won't include them.
I did the bridging header and all that.
I am trying to use them in the initial load of the Swift app:
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool
{
let testStandardConst:StandardEnumType = translateIntToEnumValue ( 0 )
// Nope.
// if ( testStandardConst.toRaw() == 0 )
// {
//
// }
// This don't work.
// if ( testStandardConst == StandardEnumType_Value0 )
// {
//
// }
// Neither does this.
// if ( testStandardConst == StandardEnumType_Value0.toRaw() )
// {
//
// }
// Not this one, either.
// if ( testStandardConst.toRaw() == StandardEnumType_Value0 )
// {
//
// }
let testAppleConst:AppleEnumType = translateIntToAppleEnumValue ( 0 )
// This don't work.
// if ( testAppleConst == AppleEnumType.AppleEnumType_Value0 )
// {
//
// }
// Neither does this.
// if ( testAppleConst == AppleEnumType.AppleEnumType_Value0.toRaw() )
// {
//
// }
// Nor this.
// if ( testAppleConst == .AppleEnumType_Value0 )
// {
//
// }
return true
}
I can't seem to get the $##!! enums to compare to either ints or anything else.
I am often humbled by the stupid errors I make, and sometimes need them pointed out to me, so please humble me.
Thanks!
When working with typedef NS_ENUM enums in swift you should omit enum name in comparison and assignment, here how you can compare it:
if ( testAppleConst == .Value0 ) { ... }
You can read more about this in Apple do s for Swift here.

How do I access an enum in Swift from Objective-C?

There is a global enum defined in Objective-C:
typedef enum {
UMSocialSnsTypeNone = 0,
UMSocialSnsTypeQzone = 10,
UMSocialSnsTypeSina = 11, //sina weibo
} UMSocialSnsType;
This code sets the sharetype of a platform:
snsPlatform.shareToType = UMSocialSnsTypeDouban;
In Swift, I want to get the sharetype of the platform:
var snstype = snsPlatform!.shareToType
println(snstype)
Result: UMSocialSnsType (has 1 child)
snstype.toRaw()
Error: UMSocialSnsType does not have a member named "toRaw"
From what I can tell, UMSocialSNSType was declared in Objective-C without using the NS_ENUM macro, so it wasn't imported as a Swift enum. That means that instead of being able to use .toRaw() or UMSocialSNSType.Douban you have to use the different enumeration values as constant structs. Unfortunately the type also doesn't have the appropriate operators (== or ~=) set up, so you have to compare the value property.
var snstype = snsPlatform!.shareToType
switch snstype.value {
case UMSocialSnsTypeDouban.value:
println("douban")
case UMSocialSnsTypeEmail.value:
println("email")
default:
println("other")
}
if snstype.value == UMSocialSnsTypeDouban.value {
println("douban")
}
The good news is that it looks like all the constants autocomplete in Xcode, so you should be able to do find the comparisons you need to do that way.
It looks like the Swift-version of the bridged typedef...enum must be something like:
struct UMSocialSnsType {
var value:Int
init(_ val:Int) {
value = val
}
}
let UMSocialSnsTypeNone = UMSocialSnsType(0)
let UMSocialSnsTypeQzone = UMSocialSnsType(10)
let UMSocialSnsTypeSina = UMSocialSnsType(11)
// etc
Whereas if it had been declared in Objective-C with the NS_ENUM macro, it would look like:
enum UMSocialSnsType: Int {
case UMSocialSnsTypeNone = 0
case UMSocialSnsTypeQzone = 10, UMSocialSnsTypeSina // etc.
}

Large number of bitwise enums

I've got a question regarding bitwise enums that I just can't seem to resolve. I've got a number of flags that are represented by a bitwise enum as in the following example:
enum
{
EnumNone=0,
EnumOne = 1<<0,
EnumTwo = 1<<1,
EnumThree = 1<<2,
EnumFour = 1<<3
};
typedef NSUInteger MyEnum;
All is fine with the above example. Based on my research and various helpful posts in stackoverflow (this for example), I've concluded that, using the above example, I'm essentially given 32 options (or shifts if you will), each option representing 1 bit in a 32-bit series of options, which basically tells me that I can go all the way to EnumThirtyTwo = 1 << 31.
My question is this:
Suppose I've more than 32, say 75 flags for example, to represent using a bitwise enum. How would that best be represented?
enum
{
EnumNone=0,
EnumOne = 1<<0,
EnumTwo = 1<<1,
EnumThree = 1<<2,
EnumFour = 1<<3,
...
...
EnumSeventyFive = 1<<75
};
typedef NSUInteger MyEnum;
Would it be a simple matter of changing the declaration of my enum type, say, to: typedef long int MyEnum; or typedef long MyEnum?
You can use a few simple macros/functions and a struct containing a char array of sufficient size - gives you call-by-value semantics, i.e. just like real enums. E.g. something along the lines of (typed directly into answer):
typedef struct
{
char bits[10]; // enough for 80 bits...
} SeventyFiveFlags;
typedef enum
{
EnumOne = 0,
...
EnumSeventyFive = 74
} SeventyFiveFlagNames;
NS_INLINE BOOL testFlag(SeventyFiveFlags flags, SeventyFiveFlagNames bit)
{
return (flags.bits[bit >> 3] & (1 << (bit & 0x7))) != 0;
}
However you can also use the bitstring(3) functions/macros if you are OK with call-by-reference semantics. These create (heap or stack) bit strings of any length. Use your enum to provide symbolic names for the bit numbers rather than masks, e.g.:
#include <bitstring.h>
typedef enum
{
EnumOne = 0,
...
EnumSeventyFive = 74,
SeventyFiveFlagsSize = 75
} SeventyFiveFlagNames;
typedef bitstr_t *SeventyFiveFlags;
// local (stack) declaration & use
SeventyFiveFlags seventyFive;
bit_decl(seventyFive, SeventyFiveFlagsSize); // declare
bit_nclear(seventyFive, EnumOne, EnumSeventyFive); // set all false
if( bit_test(seventyFive, EnumFortyTwo) ) // test
You can always wrap this up as a class if heap allocation only is OK.
Maybe I am talking about something irrelevant.
I think having too much flag in an enum is not a good practise. Having this large amount of flag, there must be ways to group them up like:
enum
{
EnumNone=0,
EnumOne = 1<<0,
EnumTwo = 1<<1,
EnumThree = 1<<2,
EnumFour = 1<<3
};
typedef NSUInteger widthRelated;
enum
{
EnumNone=0,
EnumOne = 1<<0,
EnumTwo = 1<<1,
EnumThree = 1<<2,
EnumFour = 1<<3
};
typedef NSUInteger heightRelated;

Is there anything like a Java enum in Objective-C?

I have a situation in Objective-C where a Java-style enum would be very helpful. I have a set of layer types, and each layer has its own persistence value associated with it (stored in seconds). I want to keep these layer types in an enum, since they're too similar to make into separate classes, like so:
typedef enum {
ExplosionLayerType,
FireworkLayerType,
FireLayerType,
FireJetLayerType
} FXLayerType;
In Java, I could easily associate these two values with something like this:
public enum FXLayerType {
Explosion(3),
Firework(6),
Fire(7),
FireJet(-1);
private int persistence;
FXLayerType(int persistence) {
this.persistence = persistence;
}
}
Is there a simple way to create a sort of lightweight class like this in Objective-C, or will need to resort to more primitive methods?
EDIT:
Various people have suggested doing something like this:
typedef enum {
ExplosionLayerType = 3,
FireworkLayerType = 6
} FXLayerType;
This will not work for me, since I may have something like this (Java-style enum):
Explosion(3),
Firework(6),
Dust(3);
In Java, Dust and Explosion will be treated as unique values, but direct assignment with C enums will treat them as being exactly the same.
If you just want a primitive container for type and value, consider this approach:
typedef struct FXLayerValue {
FXLayerType type;
int value;
} FXLayerValue;
Then again, a class hierarchy may be worth consideration if things become complex or are better handled dynamically. Caveat: if you have a ton of objects to save and/or create, an objc type will be overkill and degrade performance.
Unfortunately, my Java-Fu isn't good enough to know all the lang differences for enums.
To emulate Java enum's we need something which is comparable (can be operands of == etc.), which can have fields, and is lightweight. This suggests structs, and optionally pointers to structs. Here is an example of the latter:
FXLayerType.h:
typedef const struct { int persistence; } FXLayerType;
extern FXLayerType * const LayerTypeExplosion;
extern FXLayerType * const LayerTypeFirework;
extern FXLayerType * const LayerTypeDust;
FXLayerType.m:
#import "FXLayerType.h"
const FXLayerType _LayerTypeExplosion = { 3 };
const FXLayerType _LayerTypeFirework = { 6 };
const FXLayerType _LayerTypeDust = { 3 };
FXLayerType * const LayerTypeExplosion = &_LayerTypeExplosion;
FXLayerType * const LayerTypeFirework = &_LayerTypeFirework;
FXLayerType * const LayerTypeDust = &_LayerTypeDust;
So FXLayerType itself is a constant struct, while as with Obj-C objects we always use pointers to these structs. The implementation creates 3 constant structs and 3 constant pointers to them.
We can now write code such as:
FXLayerType *a, *b;
a = LayerTypeDust;
b = LayerTypeExplosion;
NSLog(#"%d, %d\n", a == b, a->persistence == b->persistence);
Which will output "0, 1" - a and b are different enums (0) but have the same persistence (1). Note here a and b are not constant pointers, only the enum "literals" are defined as constants.
As written this has the disadvantage that you cannot switch on an enum value. However if that is needed just add a second field, say tag, and init it with a unique value using a real enum, say FXLayerStyleTag. You can also remove the indirection if you are happy to always compare tags (e.g. a.tag ==b.tag`). This gives you:
FXLayerType.h:
typedef enum { ExplosionTag, FireworkTag, DustTag } FXLayerTypeTag;
typedef struct { FXLayerTypeTag tag; int persistence; } FXLayerType;
extern const FXLayerType LayerTypeExplosion;
extern const FXLayerType LayerTypeFirework;
extern const FXLayerType LayerTypeDust;
FXLayerType.m:
#import "FXLayerType.h"
const FXLayerType LayerTypeExplosion = { ExplosionTag, 3 };
const FXLayerType LayerTypeFirework = { FireworkTag, 6 };
const FXLayerType LayerTypeDust = { DustTag, 3 };
Use:
FXLayerType a, b;
a = LayerTypeDust;
b = LayerTypeExplosion;
NSLog(#"%d, %d\n", a.tag == b.tag, a.persistence == b.persistence);
A difference between the two designs is the first passes around pointers while the second structures, which may be larger. You can combine them, to get switchable pointer-based enums - that is left as an exercise!
Both these designs also have the (dis)advantage that the number of enum "literals" can be extended at any time.
Actually you may assign values to the enum keys in C, as they are nothing but ints:
typedef enum {
LayerTypeExplosion = 3,
LayerTypeFirework = 6,
LayerTypeFire = 7,
LayerTypeFireJet = -1
} FXLayerType;
You may use them then simply as a restricted set of values, to be assigned to a variable of type FXLayerType.
FXLayerType myLayerType = LayerTypeFirework;
NSLog(#"Value of myLayerType = %i", myLayerType);
// => "Value of myLayerType = 6"
This is not 100% equivalent, but this might be an approach you could take in Objective-C. Basically, create several class-level convenience methods to construction the various configuration of FXLayerType.
#interface FXLayerType
{
#private
int persistence;
}
+ (FXLayerType*)fireworkLayerType;
+ (FXLayerType*)explosionLayerType;
+ (FXLayerType*)jetLayerType;
#end
#implementation FXLayerType
+ (FXLayerType*)explosionLayerTypeWithPersistence:(int)persistence
{
FXLayerType* layerType = [[FXLayerType new] autorelease];
layerType->persistence = persistence;
return layerType;
}
+ (FXLayerType*)explosionLayerType
{
return [self explosionLayerTypeWithPersistence:3];
}
+ (FXLayerType*)fireworkLayerType
{
return [self explosionLayerTypeWithPersistence:6];
}
+ (FXLayerType*)jetLayerType
{
return [self explosionLayerTypeWithPersistence:-1];
}
#end
Usage:
FXLayerType* aJetLayerType = [FXLayerType jetLayerType];
I have recently used the j2objc format for enums. It works rather nicely. Additionally you can auto generate your enums if you are trying to map directly from a java object.
https://code.google.com/p/j2objc/wiki/Enums
However, I did remove the j2objc specific classes from my "Enums". I did not want the additional dependencies.
The struct based answers look good on their face but fail when you try to add Objective-C objects into the struct. Given that limitation, truly emulating the Java-style enum may be more work than it is worth.