iphone - 如何将字符串从 Objective-C 传递给 C 函数并取回值?

标签 iphone objective-c c

我有一个 Objective-C View Controller 类,我试图从中调用直接 C(不是 Objective-C)函数。我想通过引用传入一个字符串变量,在 C 函数中设置它的值,然后回到我的 View Controller 中,我想将它转换为一个普通的 NSString 对象。

由于无法直接传入NSString对象,我需要创建并传入一个char指针或char数组,然后将其转换为函数返回后的 NSString 对象。

谁能给我指出一个简单的代码示例来说明如何执行此操作?我不擅长 Objective-C 或常规 C,因此操作字符串对我来说非常困难。

最佳答案

也许是这样的

bool doSomethingToMyString(const char* originalString, char *buffer, unsigned int size)
{
    bool result = 0;
    if (size >= size_needed)
    {
        sprintf(buffer, "The new content for the string, maybe dependent on the originalString.");
        result = 1;
    }
    return result;
}

...
- (void) objectiveCFunctionOrSomething:(NSString *)originalString
{
    char myString[SIZE];
    if (doSomethingToMyString([originalString UTF8String], myString, SIZE))
    {
        NSString *myNSString = [NSString stringWithCString:myString encoding:NSUTF8StringEncoding];
        // alright!
    }
}

或者,您知道,类似的东西。

关于iphone - 如何将字符串从 Objective-C 传递给 C 函数并取回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3942513/

相关文章:

iphone - 如何将选项卡栏 Controller 添加到 Split View Controller 应用程序的 Root View

iphone - ios - 如何用名称初始化数组?

c - 读取器进程在 FIFO 文件关闭时终止

iphone - OpenCv - iOS MapKit 冲突

ios - 在另一个导航 Controller 上弹出导航 Controller

iphone - UITableViewCell 的动态高度取决于文本

c - pcap_open_dead 模拟完整的 UDP 数据包捕获

c - sockaddr_in 不支持地址族

jquery - 使用 HTML5、CSS3 和 jQuery 的 iPhone 应用程序

ios - initWithCoder : function is not called from unarchiveObjectWithData: