使用本机代码时Unity崩溃

时间:2012-06-28 10:46:27

标签: c# objective-c xcode plugins unity3d

所以我尝试在Xcode中统一和客观c代码中传递c#代码。 这是我的代码:

text.h

extern "C" {
int textTotexture(int hello,int world);
}

text.mm

int textTotexture(int hello,int world){
NSString *myString =[[NSString alloc] init];
NSSize size = [myString sizeWithAttributes:0];
NSImage* newImage = [[NSImage alloc] initWithSize: size]; 
[newImage lockFocus]; 

/* if you have a second image you're going to overlay on top of the first, do the same except use NSCompositeSourceOver as the operation */
//NSRect myRect = NSMakeRect(0,0,size.width,size.height);

//[myString drawInRect:myRect withAttributes:0]; 
[newImage unlockFocus];
//NSData *imageData = [newImage TIFFRepresentation];
//NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
//NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] forKey:NSImageCompressionFactor];
//imageData = [imageRep representationUsingType:NSPNGFileType properties:imageProps];
//int len = [imageData length];
//memcpy(data, [imageData bytes], len);
return hello+world;
}

调用函数:

[DllImport("CubePlugin")]
public static extern int textTotexture(int s, int w);
Debug.Log(textTotexture(1,2));

基本通信很好,因为调试日志返回3.但是一旦我添加了功能代码,统一就会崩溃。我怀疑一些本机代码没有运行到最后。

我刚刚发现当我添加锁定焦点并失去焦点时会出现问题。我该怎么做才能避免这样做而是实现我的目标?

1 个答案:

答案 0 :(得分:0)

你的班级“文本”的处理方式并不明显,但你可以试试这个:(我在没有编辑的情况下写作,所以可能会有拼写错误)

@implementation text
//.... 
-(int)textToTexture:(int)A andValue:(int)B
{
   int result = 0;
   // do stuff
   return result
}
@end

static text* myObject = nil;

extern "C"{
   int textToTexture(int a, int b)
  {
     if(myObject == nil)
         myObject = [[text alloc] init];

     return [myObject textToTexture:a andValue:b];
  }
}

在C#文件中

[DllImport ("__Internal")]
public static extern int textTotexture(int a, int b);

然后调用函数