在ruby中如何调用c、c++或java的函数求答案

Python014

在ruby中如何调用c、c++或java的函数求答案,第1张

知道在java中调用c或c++函数,主要是通过本地化接口jni来实现的,在windows下,调用的是dll文件,在unix下,调用的是so文件。也有使用java-corba-c++通信模式的。

关于 RubyMotion 我已经写过很多文章了,但如何混用Objective-C与Ruby还从未涉及到。实际上你能在RubyMotion项目中使用Objective-C代码,也可以在传统Objective-C的App中使用Ruby代码。也许你一次听来觉得像黑魔法一样,所以来一起看看下面这些示例。

Objective-C in Ruby

很多iOS开发者在现有的Objecive-C代码中存在大量深层的备份日志,这样就为项目手动转换为 RubyMotion 带来了很大的痛苦。然而幸运的是现在仅仅只需要将编译好的Objective-C代码添加到我们的新RubyMotion应用里。

比如我们要在 RubyMotion 应用中使用 Objective-C 形式的 CYAlert 类:

// CYAlert.h

#import <UIKit/UIKit.h>@interface CYAlert : NSObject

+ (void)show@end

// CYAlert.m

#import "CYAlert.h"

@implementation CYAlert

+ (void)show {

UIAlertView *alert = [[UIAlertView alloc] init]

alert.title = @"This is Objective-C"

alert.message = @"Mixing and matching!"

[alert addButtonWithTitle:@"OK"]

[alert show]

[alert release]

}@end

为了在RubyMotion应用中能正常使用,这里需要将CYAlert的两个文件都放置到类似 ./vendor/CYAlert 里面,然后在 Rakefile: 中告诉 RubyMotion 使用vendor_project创建那个文件夹。

Motion::Project::App.setup do |app|

# Use `rake config' to see complete project settings.

app.name = 'MixingExample'

# ./vendor/CYAlert contains CYAlert.h and CYAlert.m

app.vendor_project('vendor/CYAlert', :static)

end

那么现在在 AppDelegate 中,我们这样使用 CYAlert:

class AppDelegate

def application(application, didFinishLaunchingWithOptions:launchOptions)

CYAlert.show

true

end

end

file = File.new("testfile.txt", "w")

file.puts "ok"

file.printf("haha:%d",12)

file.close