objective-c - C 函数可以用作 Cocoa 中的选择器吗?

标签 objective-c c multithreading selector

我想使用 C 函数而不是 Objective-C 方法来启动一个新线程。我试过了

[NSThread detachNewThreadSelector: @selector(func) toTarget: nil withObject: id(data)];

我在哪里

void func(void *data) {
   // ...
}

datavoid *,但我在objc_msgSend 中遇到运行时崩溃,从

调用
-[NSThread initWithTarget:selector:object:]

我能做什么呢?有可能吗?

最佳答案

自己动手:

// In some .h file.  #import to make the extension methods 'visible' to your code.
@interface NSThread (FunctionExtension)
+(void)detachNewThreadByCallingFunction:(void (*)(void *))function data:(void *)data;
-(id)initWithFunction:(void (*)(void *))function data:(void *)data;
@end

// In some .m file.
@implementation NSThread (FunctionExtension)

+(void)startBackgroundThreadUsingFunction:(id)object
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  void (*startThreadFunction)(void *) = (void (*)(void *))[[object objectForKey:@"function"] pointerValue];
  void *startThreadData               = (void *)          [[object objectForKey:@"data"] pointerValue];

  if(startThreadFunction != NULL) { startThreadFunction(startThreadData); }

  [pool release];
  pool = NULL;
}

+(void)detachNewThreadByCallingFunction:(void (*)(void *))function data:(void *)data
{
  [[[[NSThread alloc] initWithFunction:function data:data] autorelease] start];
}

-(id)initWithFunction:(void (*)(void *))function data:(void *)data
{
  return([self initWithTarget:[NSThread class] selector:@selector(startBackgroundThreadUsingFunction:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSValue valueWithPointer:function], @"function", [NSValue valueWithPointer:data], @"data", NULL]]);
}

@end

注意:我写了上面的代码,并把它放在了公共(public)领域。 (有时律师喜欢这种东西)它也完全未经测试!

如果你能保证线程入口函数也创建一个,你总是可以删除 NSAutoreleasePool 位......但它是无害的,没有任何速度损失,并且可以任意调用C 函数要简单得多。我会说就把它放在那里。

你可以像这样使用它:

void bgThreadFunction(void *data)
{
  NSLog(@"bgThreadFunction STARTING!! Data: %p", data);
}

-(void)someMethod
{
  // init and then start later...
  NSThread *bgThread = [[[NSThread alloc] initWithFunction:bgThreadFunction data:(void *)0xdeadbeef] autorelease];
  // ... assume other code/stuff here.
  [bgThread start];

  // Or, use the all in one convenience method.
  [NSThread detachNewThreadByCallingFunction:bgThreadFunction data:(void *)0xcafebabe];
}

运行时:

2009-08-30 22:21:12.529 test[64146:1303] bgThreadFunction STARTING!! Data: 0xdeadbeef
2009-08-30 22:21:12.529 test[64146:2903] bgThreadFunction STARTING!! Data: 0xcafebabe

关于objective-c - C 函数可以用作 Cocoa 中的选择器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1355045/

相关文章:

c - 链接到 libGL 添加了对 NVidia 库的引用

c - C中的char * []的范围是什么?

用VC++编译C程序[2005]

java - 实现线程接口(interface)

objective-c - stringByAppendingString 导致系统用完应用程序的内存

objective-c - 如何使用NStimer同步iPhone SDK中的音频?

c++ - Minimax 算法中的线程

node.js - node-opencv npm - 即使 Node 是单线程的,它也会进行多线程计算吗?

ios - 根据值(360)或百分比(100%)创建彩色圆圈

ios - UIScrollView 做空白并且不滚动