Calling a Pascal Function from C

The example below demonstrates a C main module calling Pascal function fact. This function returns the factorial of an integer value.

/* C source file - calls Pascal function.

* Compile in medium or large model.

*/

int __pascal fact(int n);

/* PASCAL keyword causes C to use FORTRAN/Pascal

* calling and naming conventions.

* Integer parameter passed by value.

*/

main()

{

int x = 3;

int y = 4;

printf( “The factorial of x is %4d”, fact( x ) );

printf( “The factorial of y is %4d”, fact( y ) );

printf( “The factorial of x+y is %4d”, fact( x + y ) );

}

{ Pascal source code - factorial function. }

MODULE Pfun;

FUNCTION Fact (n : INTEGER) : INTEGER;

{Integer parameters received by value, the Pascal default. }

BEGIN

Fact := 1;

WHILE n > 0 DO

BEGIN

Fact := Fact * n;

n := n - 1; {Parameter n modified.}

END;

END;

END.

In the example above, the C program adopts the Pascal naming convention and calling convention. Both programs must agree on whether parameters are passed by reference or by value. The __pascal keyword directs C to call fact with the FORTRAN/Pascal naming convention (as FACT); __pascal also directs C to call fact with the FORTRAN/Pascal calling convention.

The Pascal function fact should receive a parameter by value. Otherwise, the Pascal function will corrupt the parameter's value in the calling module. Passing by value is the default method for both C and Pascal.