Example of C Function Returning a String to Basic (47756)



The information in this article applies to:

  • Microsoft QuickBASIC 4.0
  • Microsoft QuickBASIC 4.0b
  • Microsoft QuickBASIC 4.5
  • Microsoft BASIC Compiler for MS-DOS and OS/2 6.0
  • Microsoft BASIC Compiler for MS-DOS and OS/2 6.0b
  • Microsoft Basic Professional Development System (PDS) for MS-DOS and MS OS/2 7.0
  • Microsoft Basic Professional Development System (PDS) for MS-DOS and MS OS/2 7.1

This article was previously published under Q47756

SUMMARY

The two programs shown below demonstrate how a C function can return a string to a compiled Basic program.

For Microsoft Basic PDS 7.00 and 7.10, this example applies only to near strings. If you are using far strings (BC /Fs on compile or when using QBX.EXE), you must use the string-manipulation routines supplied with Basic PDS 7.00 and 7.10 (StringAssign, StringRelease, StringAddress, and StringLength). For more information about far strings, see Chapter 13 of "Microsoft Basic 7.0: Programmer's Guide" for versions 7.00 and 7.10.

MORE INFORMATION

For more information about passing other types of parameters between Basic and C and a list of which Basic and C versions are compatible with each other, query in the Microsoft Knowledge Base using the following word:

BAS2C

Code Example

The following Basic program is BSTRF.BAS, which calls the C function and prints out the returned string and its length:
   DECLARE FUNCTION CFUNC$ CDECL ()
   a$ = CFUNC$
   PRINT a$
   PRINT len(a$)
				
The following program is CSTRF.C, which builds a string descriptor that is passed back to the calling Basic program:
#include <string.h>
struct stringdesc
       {
        int length;        /* length of the string */ 
        char *string;      /* near pointer to the string */ 
       };
struct stringdesc *std;
char thestring[18];      /* In the medium memory model this  */ 
                         /* string will be in DGROUP - which */ 
                         /* is required for Basic    */ 
struct stringdesc *cfunc()
{
  std->length = 18;      /* length of the string */ 
  strcpy(thestring, "This is the string");
  std->string = thestring;
  return(std);           /* return pointer to string descriptor */ 
}
				
To demonstrate these programs from an .EXE program, compile and link as follows:
   BC BSTRF.BAS;
   CL /c /AM CSTRF.C;
   LINK /NOE BSTRF CSTRF;
				
BSTRF.EXE produces the following output:

This is the string
18


Modification Type:MinorLast Reviewed:8/16/2005
Keywords:KB47756