Using c library in objective c - iphone

I'm having trouble creating this c struct in objective c.
typedef struct huffman_node_tag
{
unsigned char isLeaf;
unsigned long count;
struct huffman_node_tag *parent;
union
{
struct
{
struct huffman_node_tag *zero, *one;
};
unsigned char symbol;
};
} huffman_node;
I'm getting this warning at the end of the union type and the end of the struct type above the "unsigned char symbol variable"
warning: declaration does not declare anything
And then when i do something like this:
huffman_node *p = (huffman_node*)malloc(sizeof(huffman_node));
p->zero = zero;
I get this compilation error:
error: 'huffman_node' has no member named 'zero'
Why does this not work? Did i set this up incorrectly? Has anyone experienced this before?

typedef struct huffman_node_tag
{
unsigned char isLeaf;
unsigned long count;
struct huffman_node_tag *parent;
union
{
struct
{
struct huffman_node_tag *zero, *one;
}; // problematic here!
unsigned char symbol;
}; // another problem here!
} huffman_node;
Depending on the C dialect/compiler that is being used to interpret the code, you may not be allowed to declare a struct or union without a name. Try giving them names and see what happens. Alternatively, you may want to try and change the C dialect you are using.

As far as I know anonymous unions are not part of C, but are a compiler extension. So strictly your given struct definition is not valid C. Consequently it seems that objective C does not supports this extension.

You need to include the header for the C library you are using.
You shouldn't have to do much else than that, as Objective C, unlike C++, is a strict superset of C.

Related

How are Swift enums implemented internally?

I recently asked a question around sort of generic enum/structs in C and realized that although I brought up a comparison with the enum possibilities in e.g. Swift and Rust, I don't really understand how those are handled internally to those languages.
For Rust, I found a (rather roundabout) article titled Peeking inside a Rust enum
— look for the "But Rust enums aren't just that." heading and then keep scrolling until the "In Rust, it's called a discriminant." part. Eventually that part gets around to basically saying that Rust enums are sort of equivalent to something like this in C:
struct {
enum actual_options discriminant;
union {
/* … various data types/sub-structs corresponding to each option's need… */
};
};
Is it basically the same with a Swift enum under the hood? I.e. that I should expect an enum to have basically the same memory overhead as a struct of the largest possible option in my enum, plus at least one extra byte to store the tag/discriminant of the overarching case?
I'm also interested in what code gets generated to use whatever sort of underlying structure. I'm assuming it can't really much more fancy/optimized than what you'd do in C for the structure shown above? E.g.
struct raw_enum {
enum { case1, case2, case3 } tag;
union {
struct { int x; int y; } case1_data;
const char* case2_data;
struct { float a; double b; void* c; char d; } case3_data;
};
};
struct raw_enum d;
fill_in_some_value(&d);
if (d.tag == case1) {
// use `d.case1_data`…
} else if (d.tag == case2) {
// use `d.case2_data`…
} else if (d.tag == case3) {
// use `d.case3_data`…
} else {
// any runtime assertion for an unknown tag that could somehow sneak in???
}
Is that a reasonable approximation to what Swift does in the code it generates around enums?

Weird issues when passing an array of structs from Swift to C

I'm passing an array of structs from Swift to a C function. The struct looks like this:
struct Struct {
int a;
float b;
float c;
const char* d;
const char* e;
const char* f;
const char* g;
int h[4];
};
Function signature of the C function:
void test(struct Struct* structs);
Weirdly, when I print d in the C function, it's often something different than what I set it to in the Swift code: usually an empty string or some garbage. When I set d to a very long string, it works correctly. The other strings are passed correctly too. Is that some struct alignment issue?
As #MartinR suggested, when I pass the string to the struct's constructor, Swift creates a temporary C char array on the stack, copies the string's data into it and passes its pointer to the constructor. Immediately after that, the char array is no longer valid. Here's an example code demonstrating this:
let s = Struct(string: "string")
print(s.string) // Prints "string"
print("lol") // Overwrite the stack
print(s.string) // Prints "lol"
See https://stackoverflow.com/a/40121697/243225 for possible solutions.

Swift define double pointer for struct defined in c

I have a library which contains this function:
void create_pointer(Pointer **pointer);
It takes a pointer's pointer and allocates memory for it. in c, I can do it like this
Pointer *pointer;
create_pointer(&pointer);
then I have a pointer's instance.
But now I want to use this function in Swift. How?
I have no details about Pointer, I only know it's a struct, defined like this
typedef struct Pointer Pointer;
Let's start with a C example
typedef struct {
NSUInteger someNumber;
} SomeStruct;
void create_some_struct(SomeStruct **someStruct) {
*someStruct = malloc(sizeof(SomeStruct));
(*someStruct)->someNumber = 20;
}
In C, you would use it like this:
//pointer to our struct, initially empty
SomeStruct *s = NULL;
//calling the function
create_some_struct(&s);
In Swift:
//declaring a pointer is simple
var s: UnsafePointer<SomeStruct> = UnsafePointer<SomeStruct>.null()
//well, this seems to be almost the same thing :)
create_some_struct(&s)
println("Number: \(s.memory.someNumber)"); //prints 20
Edit:
If your pointer is an opaque type (e.g. void *), you have to use
var pointer: COpaquePointer = COpaquePointer.null()
Note that Swift is not designed to interact with C code easily. C code is mostly unsafe and Swift is designed for safety, that's why the Swift code is a bit complicated to write. Obj-C wrappers for C libraries make the task much easier.

multiple typedef for same type in c

I have seen multiple typedef for same type in c
typedef struct i_data
{
uint32 size;
uint8 *data;
} I_DATA, *I_DATA_PTR;
typedef I_DATA I_TEMP;
typedef I_DATA *I_TEMP_PTR;
typedef I_DATA I_SEARCH_TEMP;
typedef I_DATA *I_SEARCH_PTR;
is it possible? How compiler distinguish all this typedef definition
yes, it's not problem. you are basically saying that they are all identical.. :)
I_DATA and I_TEMP and I_SEARCH_TEMP are the same thing, typedefs of the i_data struct.
I_DATA_PTR and I_TEMP_PTR and I_SEARCH_PTR are the same thing, pointers to a typedef of the i_data struct.
If they are all the same, in theory why does the compiler need to tell them apart?
It's a little like a person that has a name and a nickname, it might not be the same name but it's still the same person ;)
Sure is possible! I couldn't tell you exactly how the compiler figures this out... I have never read into the inner workings of compilers. I do know that multiple type definitions for the same type are not a problem!

Why we used double and triple pointer in objective-C or C language?

I confused when i want to take single pointer and when should i take double pointer?
In following structure what exactly did?
struct objc_class {
Class isa;
Class super_class;
const char *name;
long version;
long info;
long instance_size;
struct objc_ivar_list *ivars;
struct objc_method_list **methodLists;
struct objc_cache *cache;
struct objc_protocol_list *protocols;
};
Why we use the methodLists double pointer?
Edited
int sqlite3_get_table(
sqlite3 *db,
const char *zSql,
char ***pazResult,
int *pnRow,
int *pnColumn,
char **pzErrmsg
);
In above scenario what will be meaning of triple pointer char ***pazResult?
Well, in C at least, double-pointers are commonly used for 2D arrays. The most common 2D array is probably an array of C strings (char*'s). Double pointers are also sometimes employed to pass pointers to functions by reference, but this is unlikely to be the use in the code sample you posted.
According to the name methodLists I would guess that this is an array of lists. A (linked) list in C is commonly represented by a pointer to a node, which objc_method_list could be. An array of such lists is then implemented with a double pointer.
It's probably not the case in the code that you referenced, but you also need a double pointer any time you want to pass a pointer to a function and have changes to that pointer be reflected outside the scope of that function.
For example, if you were trying to rewrite the strcpy function so that the user did not have to allocate memory for the source string, you might try something like the following:
void MyStrcpy(char* dst, char* src){
dst = (char*)malloc(sizeof(char)*(strlen(src)+1));
for(int i=0;i<=strlen(src);i++)
dst[i] = src[i];
printf("src: %s ", src);
printf("dst: %s\n\n", dst);
}
If you were then to call that function,
int main() {
char *foo = "foo";
char *newPtr;
MyStrcpy(newPtr, foo);
printf("foo: %s ", foo);
printf("new: %s\n", newPtr);
}
your output would be as follows:
src: foo
dst: foo
foo: foo
new:
You might also get a seg fault when trying to print newPtr, depending your system. The reason for this behavior is the exact same as the reason you wouldn't expect a change to an int that was passed by value to a function to be reflected outside of that function: what you are passing to MyStrcpy is simply the memory address that newPtr references. When you malloc the space for dst inside the function, you are changing the address dst points to. This change will not be reflected outside of the scope of MyStrcpy!
Instead, if you wanted newPtr to point to the new allocated chunk of memory, you need to have dst be a pointer to a pointer, a char **.
void MyStrcpy(char** dst, char* src){
*dst = (char*)malloc(sizeof(char)*(strlen(src)+1));
for(int i=0;i<=strlen(src);i++)
(*dst)[i] = src[i];
printf("src: %s ", src);
printf("dst: %s\n\n", *dst);
}
Now, if you were to call that function:
int main() {
char *foo = "foo";
char *newPtr;
MyStrcpy(&newPtr, foo);
printf("foo: %s ", foo);
printf("new: %s\n", newPtr);
}
You would get your expected output:
src: foo
dst: foo
foo: foo
new: foo
Hope that helps!
See also these questions:
What is double star?
Why does NSError need double indirection? (pointer to a pointer)
In the most general case a double pointer is a pointer to a list of pointers.
In general pointer is used to hold the address of another variable. What if we need to hold the address of pointer ,in that case we use double pointer. When we want to hold the address of double pointer we use triple pointer.