Pointer dereferencing Swift - swift

In C & Objective C, we used to dereference a pointer and get the value as follows:
p->a = 1
or int x = p->a
But I can't find an equivalent in Swift. I have a return type UnsafePointer to AudioStreamBasicDescription? whose member values I need to read.

You use the pointee property on your UnsafePointer to access the memory it points to. So your C example would read as let x = p.pointee.a.

Related

How to get an array from a C function in Swift?

I am working with a C function in my Swift code that outputs an array. The function doesn't return an array because, apparently in C, functions are discouraged from returning arrays. Therefore, the function takes an in-out parameter (as a pointer) and places the array there.
The C function:
void kRing(H3Index origin, int k, H3Index* out);
H3Index* is the out parameter that takes the array. However, how do I get the array from this function in Swift? H3Index*, the out parameter, points to an integer. And, apparently in C, you can point to an integer, pass that pointer to a function, and that function can place an array in that pointer's place (even though it's pointing to an integer).
But because of Swift's type safety, this makes it difficult to get the array from the function. The Swift version:
kRing(origin: H3Index, k: Int32, out: UnsafeMutablePointer<H3Index>!)
My Swift implementation:
let h3Index: H3Index = 600022775385554943 // integer
let k: Int32 = 2 // integer
var result = H3Index() // the in-out parameter (must be integer to satisfy Swift's type safety)
_ = withUnsafeMutablePointer(to: &result) { kRing(h3Index, k, $0) }
print(result)
And it prints the result (with a bad access error, which I don't care about right now). But the result is an integer when it should be an array. How is this done?
The C implementation, for reference:
H3Index indexed = 0x8a2a1072b59ffffL; // 64-integer (hex)
int k = 2; // integer
int maxNeighboring = maxKringSize(k); // integer
H3Index* neighboring = calloc(maxNeighboring, sizeof(H3Index)); // the out parameter (a pointer to an integer and/or array)
kRing(indexed, k, neighboring); // the function
for (int i = 0; i < maxNeighboring; i++) {
if (neighboring[i] != 0) {
// iterate through array
}
}
In C,
H3Index* neighboring = calloc(maxNeighboring, sizeof(H3Index));
kRing(indexed, k, neighboring);
allocates memory for maxNeighboring elements of type H3Index and initializes the memory to zero. The address of that memory block (which is the address of the first element) is then passed to the kRing function.
It is possible to call calloc and free from Swift, but the easier to use API is Unsafe(Mutable)(Buffer)Pointer with its allocate() and deallocate() methods:
let neighboring = UnsafeMutableBufferPointer<H3Index>.allocate(capacity: maxNeighboring)
neighboring.initialize(repeating: 0)
kRing(indexed, k, neighboring.baseAddress)
Now you can print the values with
for i in 0..<maxNeighboring { print(neighboring[i]) }
or justs (because Unsafe(Mutable)BufferPointer is a collection that can be iterated over):
for neighbor in neighboring { print(neighbor) }
Eventually you must release the memory to avoid a memory leak:
neighboring.deallocate()
A simpler solution is to define a Swift array, and pass the address of the element storage to the C function:
var neighboring = Array<H3Index>(repeating: 0, count: maxNeighboring)
kRing(indexed, k, &neighboring)
for neighbor in neighboring { print(neighbor) }
neighboring is a local variable now, so that the memory is automatically released when the variable goes out of scope.

How does dereference work C++

I have trouble understanding what happens when calling &*pointer
int j=8;
int* p = &j;
When I print in my compiler I get the following
j = 8 , &j = 00EBFEAC p = 00EBFEAC , *p = 8 , &p = 00EBFEA0
&*p= 00EBFEAC
cout << &*p gives &*p = 00EBFEAC which is p itself
& and * have same operator precedence.I thought &*p would translate to &(*p)--> &(8) and expected compiler error.
How does compiler deduce this result?
You are stumbling over something interesting: Variables, strictly spoken, are not values, but refer to values. 8 is an integer value. After int i=8, i refers to an integer value. The difference is that it could refer to a different value.
In order to obtain the value, i must be dereferenced, i.e. the value stored in the memory location which i stands for must be obtained. This dereferencing is performed implicitly in C whenever a value of the type which the variable references is requested: i=8; printf("%d", i) results in the same output as printf("%d", 8). That is funny because variables are essentially aliases for addresses, while numeric literals are aliases for immediate values. In C these very different things are syntactically treated identically. A variable can stand in for a literal in an expression and will be automatically dereferenced. The resulting machine code makes that very clear. Consider the two functions below. Both have the same return type, int. But f has a variable in the return statement which must be dereferenced so that its value can be returned (in this case, it is returned in a register):
int i = 1;
int g(){ return 1; } // literal
int f(){ return i; } // variable
If we ignore the housekeeping code, the functions each translate into a sigle machine instruction. The corresponding assembler (from icc) is for g:
movl $1, %eax #5.17
That's pretty starightforward: Put 1 in the register eax.
By contrast, f translates to
movl i(%rip), %eax #4.17
This puts the value at the address in register rip plus offset i in the register eax. It's refreshing to see how a variable name is just an address (offset) alias to the compiler.
The necessary dereferencing should now be obvious. It would be more logical to write return *i in order to return 1, and write return i only for functions which return references — or pointers.
In your example it is indeed illogical to a degree that
int j=8;
int* p = &j;
printf("%d\n", *p);
prints 8 (i.e, p is actually dereferenced twice); but that &(*p) yields the address of the object pointed to by p (which is the address value stored in p), and is not interpreted as &(8). The reason is that in the context of the address operator a variable (or, in this case, the L-value obtained by dereferencing p) is not implicitly dereferenced the way it is in other contexts.
When the attempt was made to create a logical, orthogonal language — Algol68 —, int i=8 indeed declared an alias for 8. In order to declare a variable the long form would have been refint m = loc int := 3. Consequently what we call a pointer or reference would have had the type ref ref int because actually two dereferences are needed to obtain an integer value.
j is an int with value 8 and is stored in memory at address 00EBFEAC.
&j gives the memory address of variable j (00EBFEAC).
int* p = &j Here you define a variable p which you define being of type int *, namely a value of an address in memory where it can find an int. You assign it &j, namely an address of an int -> which makes sense.
*p gives you the value associated with the address stored in p.
The address stored in p points to an int, so *p gives you the value of that int, namely 8.
& p is the address of where the variable p itself is stored
&*p gives you the address of the value the memory address stored in p points to, which is indeed p again. &(*p) -> &(j) -> 00EBFEAC
Think about &j itself (or even &(j)). According to your logic, shouldn't j evaluate to 8 and result in &8, as well? Dereferencing a pointer or evaluating a variable results in an lvalue, which is a value that you can assign to or take the address of.
The L in "lvalue" refers to the left in "left hand side of the assignment", such as j = 10 or *p = 12. There are also rvalues, such as j + 10, or 8, which obviously cannot be assigned to.
That's just a basic explanation. In C++ there's a lot more to it, with various classes of values (but that thread might be too advanced for your current needs).

Pass Simulink.Parameter to C S-function

How does one pass a Simulink.Parameter structure (which, in my case, is a structure of structures) to a C S-function?
Edit:
Information on Simulink.Parameter
You can create a Simulink.Parameter object this way:
modelParameters = Simulink.Parameter;
modelParameters.Value = myStruct;
modelParameters.CoderInfo.StorageClass = 'ExportedGlobal';
The myStruct value is a regular matlab structure of structures. This is how it looks in my case:
This is a special object type for passing parameters to Simulink and I am looking for a mechanism to access it from a C S-function.
Download a MnWE from here.
Edit 2:
I read the parameters this way:
modelParameters_T *modelParameters = (modelParameters_T*)mxGetPr(ssGetSFcnParam(S, PARAM_STRUCT));
But I can see why this approach doesn't work - the structure object from Matlab is not similar to a C structure, i.e. is not contiguous in memory and contains other properties too. I think I will cast the Matlab structure to an array and then cast the array in C to my struct definition.
mxGetPr is not the right way to access your parameter which is an object type. It is not a struct type. Even if it is a struct type you need to use mxArray API to access struct fields. You need to use something like the following code to access the fields.
mxArray* param = ssGetSFcnParam(S, PARAM_STRUCT);
mxArray* prop = mxGetProperty(param, 0, "Value"); // Get Value property from param object
// If prop is double precision use the following line to get its value
double* prop = *(mxGetPr(prop));
Check out mxArray API in the doc for accessing different types of mxArrays.

objective-c variable length array global scope

is it possible to declare a variable length array with global scope in objective-c?
I'm making a game with a world class, which initializes the world map as a three dimensional integer array. while it's only a two dimensional side scroller, the third dimension of the list states which kinda of block goes at the coordinate given by the first two dimensions
after the initialization function, a method nextFrame: is scheduled (I'm using cocos2d and the CCDirector schedule method). I was wondering how to pass the int[][][] map array from the initialization function to the nextFrame function
I tried using global (static keyword) declaration, but got an error saying that global arrays cannot be variable length
the actual line of code I'm referring to is:
int map[xmax][ymax][3];
where xmax and ymax are the farthest x and y coordinates in the list of coordinates that defines the stage.
I'd like to somehow pass them to nextFrame:, which is scheduled in
[self schedule:#selector(nextFrame:)];
I realize I can use NSMutableArray, but NSMutableArray is kinda a headache for 3-dimensional lists of integers (I have to use wrapper numbers for everything...). is there any way to do this with integer arrays?
You can't have a statically allocated global array of dynamic dimensions in C (of which Objective C is a clean superset). But you can use a global array of any length or size (up to available memory) at runtime by using a global pointer, malloc, and array indexing arithmetic.
static int *map = NULL;
...
map = malloc (dim1 * dim2 * dim3 * sizeof(int)); // in some initialization method
if (map == NULL) { /* handle error */ } // before first array access
...
myElement = map[ index3 + dim2 * ( index2 + dim1 * index1 ) ]; // some macro might be suitable here
Or you could make Objective C getter and setter methods that checks the array and array bounds on every access, since a method can return plain C data types.
Another option, if you know the max dimensions you want to have available and are willing to use (waste) that amount of memory, is to just statically allocate the max array, and throw an exception if the program tries to set up something larger than your allowed max.
I tried using global (static keyword)
declaration, but got an error saying
that global arrays cannot be variable
length
But global array pointers can point to arrays of variable length.

IPhone SDK - How to detect variable type (float or double)?

How do I detect whether a variable is float, double, int, etc.?
Thanks.
Objective-C is not like PHP or other interpreted languages where the 'type' of a variable can change according to how you use it. All variables are set to a fixed type when they are declared and this cannot be changed. Since the type is defined at compile time, there is no need to query the type of a variable at run-time.
For example:
float var1; // var1 is a float and can't be any other type
int var2; // var2 is an int and can't be any other type
NSString* var3; // var3 is a pointer to a NSString object and can't be any other type
The type is specified before the variable name, also in functions:
- (void)initWithValue:(float)param1 andName:(NSString*)param2
{
// param1 is a float
// param2 is a pointer to a NSString object
}
So as you can see, the type is fixed when the variable is declared (also you will notice that all variables must be declared, i.e. you cannot just suddenly start using a new variable name unless you've declared it first).
In a compiled C based language (outside of debug mode with symbols), you can't actually "detect" any variable unless you know the type, or maybe guess a type and get lucky.
So normally, you know and declare the type before any variable reference.
Without type information, the best you can do might be to dereference a pointer to random unknown bits/bytes in memory, and hopefully not crash on an illegal memory reference.
Added comment:
If you know the type is a legal Objective C object, then you might be able to query the runtime for additional information about the class, etc. But not for ints, doubles, etc.
Use sizeof. For double it will be 8. It is 4 for float.
double x = 3.1415;
float y = 3.1415f;
printf("size of x is %d\n", sizeof(x));
printf("size of y is %d\n", sizeof(y));