Converting CFData to C-String

1.2k views Asked by At

I wanted to get gpu name, and found the code that does this using IOKit. The only problem is that this code was in Objective-C, while my project is in C, and I don't know how to use C-string instead of NSString.

const void *GPUModel = CFDictionaryGetValue(serviceDictionary, CFSTR("model"));

            if (GPUModel != NULL) {
                if (CFGetTypeID(GPUModel) == CFDataGetTypeID()) {
                    //(Original Comment) Create a string from the CFDataRef.
                    //NSString *modelName = [[NSString alloc] initWithData:
                    //                       (NSData *)GPUModel encoding:NSASCIIStringEncoding];

                }
            }

2

There are 2 answers

3
AudioBubble On

Solution thanks to Cy-4AH and Rob Napier.

const char *gpu_name = (char *)CFDataGetBytePtr(GPUModel);
return gpu_name;
1
SANDRUX On

C-like strings are actually char pointers aka char array, that stores each character. In the case of Obj-c NSString is a class that has a char array inside, and those methods that are used to modify your string value are just methods, and NSString itself uses C-style strings such as char array. So if you want to work with a C-style string you Have to use char arrays that is compatible with Obj-C because it is just a primitive data type.

If you will need further assistance, feel free to reply. Best, regards.