Edward Pizzurro
Edward Pizzurro

Reputation: 593

Getting null when converting const char* to NSString Objective-C

I'm trying to convert a const char* that I'm getting from a C++ method that I have, to a NSString in a method in Objective-C. This is the method from c++:

#define EXPORT __attribute__((visibility("default")))
EXPORT
string getAudioWmark(const char* _filename)
{
    string filename = string(_filename);
    string result;
    result = get_watermark(filename, "");
    
    return (result.c_str());
}

This is what result is returning in the debugger view:

result  std::string "pattern  0:00 f59e26b2f4668d02bd33e03a1c0d8892 0.774 0.774 CLIP-A\n\n"

This is the declaration of the method in the .h file from Objective-C:

extern const char* getAudioWmark(const char* filename);

@interface WatermarkLib : NSObject

- (void)getAudio:(NSString*)filename;

@end

And this is the .mm implementation of the method:

- (void)getAudio:(NSString*)filename {
    
    const char *cString = [filename cStringUsingEncoding:NSASCIIStringEncoding];
    NSString* externalString = [NSString stringWithCString:getAudioWmark(cString) encoding:NSUTF8StringEncoding];
    
    NSLog(@"Exito! %@", externalString);
}

"externalString" is null, and that's what I'm trying to fix.

Upvotes: 0

Views: 368

Answers (1)

Ol Sen
Ol Sen

Reputation: 3368

This should help you out.

const char *cString = filename.UTF8String;

But make sure filename has content otherwise it must result in null

Upvotes: 1

Related Questions