Invalid Xcode transform when using objective-c ++

So if I run my program with the implementation as .m it works fine. Just changing it to .mm this line ...

CGContextRef myContext = [[NSGraphicsContext currentContext] graphicsPort];

      

to throw this error ...

error: invalid conversion from 'void*' to 'CGContext*'

      

Anyone have any ideas why just change this so it explodes or how to fix it?

+1


source to share


2 answers


C ++ does not allow implicit type casting from void*

. In this case, implicit conversion from void*

(return type -[NSGraphicsContext graphicsPort]

) a CGContextRef

is illegal. You can make the conversion explicit like this:

CGContextRef myContext = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);

      



See this SO question for a discussion of the C ++ operator static_cast

.

+2


source


C allows you to convert void * to an arbitrary type, C ++ doesn't. Once your file is .mm, it is compiled as C ++:

cristi:tmp diciu$ cat test.c
int main()
{
    char * t = "test";
    void * m = t;
    char * g;

    g=m;

}

cristi:tmp diciu$ g++ test.c
test.c: In function ‘int main()’:
test.c:7: error: invalid conversion from ‘void*’ to ‘char*’

cristi:tmp diciu$ gcc test.c

      



To fix, cast to the correct type, that is, explicitly pass "void *" to "CGContext *".

+1


source







All Articles