Re: Can I call Obj-C from a C++ source?



Steve555:

My project is Objective-C++, but from one of the C++ classes I want to
write to the log window:

long val = 123;
NSString nsStr = [NSString stringWithFormat:@"%d", val];
NSLog(nsStr);

That's a very bad habit. The correct code is:
NSLog(@"%d", val);

In your case there's no practical difference, but if nsStr had a %@ and took a
string, it might end up with a % sequence in it, and then NSLog() would print
bad data or crash. If the string being substituted in was user input, you'd be
vulnerable to a format string attack.

That said, if you want to use NSLog from C or C++ code, and have a real reason
not to turn it into an Objective-C or Objective-C++ file, you can declare
NSLog as:
extern void NSLog(CFStringRef format, ...);

then call it as:
NSLog(CFSTR("%d"), val);

This won't port to other OpenStep implementations such as GNUstep.


--
Jens Ayton
.



Relevant Pages

  • Re: Can I call Obj-C from a C++ source?
    ... write to the log window: ... If the string being substituted in was user input, ... That said, if you want to use NSLog from C or C++ code, and have a real reason ... Jens Ayton ...
    (comp.sys.mac.programmer.help)
  • Re: Java program is not evaluating String value correctly...
    ... >:State Abbreviation and compare it for state specific programming. ... >:When it wasn't falling through the correct code, ... The way I'm filling the state abbreviation string ...
    (comp.lang.java.programmer)
  • Re: Field form
    ... >I would like to know how is the correct code that use inside the filed ... Function Combined(Invinitiv As String, Im1 As String) As String ... Dim MyArray() ...
    (microsoft.public.access.forms)
  • Re: [C] simple string question
    ... > Alan wrote: ... >> then in a function at some time, I want to set the string to a ... >> what is the correct code? ... the program crashes ...
    (alt.comp.lang.learn.c-cpp)
  • Re: [C] simple string question
    ... > Alan wrote: ... >> then in a function at some time, I want to set the string to a ... >> what is the correct code? ... the program crashes ...
    (comp.lang.c)