在X10里加入C++或者Java代码

The primary mechanism X10 programmers should use is annotations. The annotations override the usual code generation strategy used by the X10 compiler, allowing the programmer to insert verbatim C++ or Java code into their X10 program.  In the following example, the string on the static method being called is used verbatim at the call site.  Because calls are expressions, the native annotation ought to be an expression too.

Test.x10
import x10.compiler.Native;

public class Test {

    // Use native code in all backends:
    @Native("c++","printf(\"Hello World!\\n\")")
    @Native("java","System.out.println(\"Hello World!\")")
    private static native def test1 () : Void;

    // Only use native code in C++ backend:
    @Native("c++","printf(\"Hello World!\\n\")")
    private static def test2 () {
        // X10 code provides behaviour for Java backend.
    }

    // Use function parameters in native code
    // #0 is the name of the class (Test in this case)
    // #1, #2, #3, etc name the parameters
    @Native("c++","printf(\"This is the number %d\\n\", (#1))")
    @Native("java","System.out.println(\"This is the number \"+(#1))")
    private static native def test3 (x:Int) : Void;

    public static def main (args:Rail[String]!) {
        test1();
        test2();
        test3(42);
    }
}
posted @ 2010-06-09 10:44  ninahan  阅读(258)  评论(0编辑  收藏  举报