swigのpointerサンプルをC#に移植
swigでC#をちょこちょこ遊んでるんですがswigのExample/charpはいまいち数が少ない。でpointerサンプルもなかったのでJavaのを見ながら移植してみた。
class Program{ static void Main(string[] args){ // First create some objects using the pointer library. System.Console.WriteLine("Testing the pointer library"); SWIGTYPE_p_int a = example.new_intp(); SWIGTYPE_p_int b = example.new_intp(); SWIGTYPE_p_int c = example.new_intp(); example.intp_assign(a,37); example.intp_assign(b,42); System.Console.WriteLine(" a ={0:X}", example.intp_value(a)); System.Console.WriteLine(" b ={0:X}", example.intp_value(b)); System.Console.WriteLine(" c ={0:X}", example.intp_value(c)); // Call the add() function with some pointers example.add(a,b,c); // Now get the result int res = example.intp_value(c); System.Console.WriteLine(" 37 + 42 " + res); // Clean up the pointers example.delete_intp(a); example.delete_intp(b); example.delete_intp(c); // Now try the typemap library // Now it is no longer necessary to manufacture pointers. // Instead we use a single element array which in Java is modifiable. System.Console.WriteLine("Trying the typemap library"); int r = 0; example.sub(37,42,out r); System.Console.WriteLine(" 37 - 42 = " + r); // Now try the version with return value System.Console.WriteLine("Testing return value"); int q = example.divide(42,37,out r); System.Console.WriteLine(" 42/37 = " + q + " remainder " + r); } }
コンパイル例。
swig -csharp example.i gcc -c -fpic *.c gcc -shared *.o -o libexample.so mcs -nologo -t:library -out:example_wrap.dll examplePINVOKE.cs example.cs SWIGTYPE_p_int.cs mcs -nologo -r:example_wrap.dll -out:runme.exe runme.cs
実行結果。
Testing the pointer library a =25 b =2A c =0 37 + 42 79 Trying the typemap library 37 - 42 = -5 Testing return value 42/37 = 1 remainder 5