代码之家  ›  专栏  ›  技术社区  ›  MusiGenesis

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

  •  1
  • MusiGenesis  · 技术社区  · 15 年前

    我有一个Objective-C视图控制器类,从中我试图调用一个直C(不是Objective-C)函数。我想通过引用传入一个字符串变量,在C函数中设置它的值,然后在视图控制器中把它转换成一个普通的NSString对象。

    char 指针或 烧焦 数组,然后在函数返回后将其转换为NSString对象。

    有人能给我举一个简单的代码示例来说明如何做到这一点吗?我在Objective-C和regular-C中都不强,所以对我来说操作字符串是非常困难的。

    4 回复  |  直到 15 年前
        1
  •  6
  •   filipe    15 年前

    也许是这样的

    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!
        }
    }
    

    或者,你知道的,一些有这种效果的东西。

        2
  •  1
  •   Nimrod    15 年前

    在中查看以下内容 NSString 文件:

    – cStringUsingEncoding:
    – getCString:maxLength:encoding:
    – UTF8String
    + stringWithCString:encoding:
    
        3
  •  0
  •   MusiGenesis    15 年前

    好吧,我开始工作了。这是我的C函数:

    int testPassingChar(char buffer[]) {    
        strcpy(buffer, "ABCDEFGHIJ");
        return 0;
    }
    

    然后从Objective-C:

    char test[10];
    int i;
    i = testPassingChar(test);
    NSString* str = [[NSString alloc] initWithBytes:test length:sizeof(test) 
        encoding:NSASCIIStringEncoding];
    
        4
  •  0
  •   diatrevolo    15 年前

    为什么不把C函数包装成Objective-C呢?

    -(NSString*)testPassingCharWithStringLength:(int)whateverLength {
         char *test = malloc(sizeof(char) * whateverLength);  
         //do whatever you need to *test here in C
         NSString *returnString = [NSString stringWithUTF8String:test];
         free(test);
         return returnString;
    }
    

    …例如。。。