从外部调用 objective-c 方法 "C"

call objective-c method from extern "C"

我有一个 temp.mm class,其中包含测试 class 和外部 "C" class 的实现。我试图在 extern "c" class 中调用 objective-c 方法(即 testMethod 和 testMethod1)。 我如何在 extern "C" class 函数中调用 objective-c 方法?

我是新手 Objective-c

我提到下面的示例代码..

import<test.h>
@implement test

-(void)testMethod
{
//code
}

-(NSString*)testMethod1:(NSString *)value
{
   //code
   return value;
}

void callMethod()
{
   how to call testMethod & testMethod1 in this also?
}

@end

extern "C"
{
how to call testMethod & testMethod1?
}

C 代码部分(并且必须)在您的 class' 实现之外,因此您必须创建 test 的 object 然后调用它的方法,如下所示:

void callMethod() 
{
    test *test = [[test alloc] init];
    [test testMethod];

    const char *yourCString = "yourCString";
    [test testMethod1:[NSString stringWithCString:yourCString encoding:NSUTF8StringEncoding]];
}

您不需要 extern "C" 实现部分(.m.mm 文件),这在 header 中只需要(.h 文件)当你想将它们标记为 "plain old c code"(不是 C++)时。

参见:Is it required to add 'extern C' in source file also?

初始时也调用方法..... 采用: 【自测方法】; [自测方法1]; 如果您想将此方法继承到另一个 class 只需导入 .m 文件即可。