Java の文字列を COBOL に渡す際に常に問題になるのが文字列長です。COBOL では、文字列は常に固定長になるからです。COBOL プログラムで定義済みの固定長フィールドに変更を加えるには、そのインスタンスを Pointer クラスの新しいインスタンスでラップする必要があります。Pointer クラスは com.microfocus.cobol.lang package で定義されています。
PIC X(20) データ項目を定義している COBOL プログラムの例を次に示します。
showbytes.cbl:
working-storage section.
linkage section.
01 lnk-string pic x(20).
procedure division using lnk-string.
display "lnk-string = " lnk-string.
move "Hello from COBOL - 1" to lnk-string.
exit program returning 0.
対応する Java のコードは次のようになります。
showbytes.java:
import com.microfocus.cobol.RuntimeSystem;
import com.microfocus.cobol.lang.Pointer;
import com.microfocus.cobol.lang.ParameterList;
public class showbytes
{
public static void main(String[] args) throws Exception
{
String myString = new String("Hello to COBOL");
Pointer ptr2String = new Pointer(myString, 20);
RuntimeSystem.cobcall("showbytes",
new ParameterList().add(ptr2String));
myString = ptr2String.toString();
System.out.println(myString = ["+myString+"]");
}
}