swig java使用例

1464 ワード

手順:
1、swig -java -c++ example.i    c++インタフェースファイルを生成します.2、VS 2010を使用してすべてのc++ファイルをコンパイルし、対応するdll(x 86またはx 64)を生成し、他のLinuxプラットフォームはso=>example.dll example.soを生成し、最後にダイナミックリンクライブラリを現在のディレクトリに置く.3、javac *.java 4、java runme
//example.cpp

double Foo=6.0;

int gcd(int x,int y)
{
    int g;
    g=y;
    while(x>0)
    {
        g=x;
        x=y%x;
        y=g;
    }
    return g;
}
%module example
#   %{ ..%}    :example.i
%inline %{
extern int gcd(int x,int y);
extern double Foo;   
%}
        
//runme.java
public class runme {

  static {
    try {
	System.loadLibrary("example");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.
" + e); System.exit(1); } } public static void main(String argv[]) { // Call our gcd() function int x = 42; int y = 105; int g = example.gcd(x,y); System.out.println("The gcd of " + x + " and " + y + " is " + g); // Manipulate the Foo global variable // Output its current value System.out.println("Foo = " + example.getFoo()); // Change its value example.setFoo(3.1415926); // See if the change took effect System.out.println("Foo = " + example.getFoo()); } }