Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28632 Discussions

Sample code for calling Fortran routine with Character argument from VB6

Leigh_Wardle1
Beginner
547 Views

Hi all,

I am looking for some sample code for calling a Fortran routine with a Character argument from Visual Basic Classic (VB6).

Thanks in advance.

Regards,

Leigh

0 Kudos
3 Replies
jimdempseyatthecove
Honored Contributor III
519 Views

This may help (from https://gamedev.net/forums/topic/289691-passing-strings-from-vb-to-c-dll/2826603/)

As HarryW already pointed out, your problem might be related to the fact the strings in VB
are always stored in unicode format with their length prepended in the 4 bytes just before
the address VB hands out which makes up the BSTR format. Their is some conversion magic in VB
which tries to convert these to plain Ascii-Z strings for calls to externals functions
imported using the 'Declare' directive, but I'm not sure on which criterions VB decides
whether a conversion is done or not.


It would however certainly be better to just wrap up the function in an ATL COM project.
C++ COM DLLs are easy to create these days with attributed ATL support in MSVC++.NET 2003
and you can with almost no effort not only export functions but entire classes as well
to your VB applications.

[ module(name=MyLibrary) ];
[ idl_module(name="BookManagement", dllname=MyLibrary.dll) ];
[ idl_module(name="BookManagement") ]STDAPI GetBookNo([in] BSTR sFilename, [out, retval] long *pResult) throw() {
if(pResult) {
::AtlSetErrorInfo( GUID_NULL, L"Return address is invalid", 0, NULL, GUID_NULL, E_FAIL, 0 );
return E_FAIL; }
ifstream file(_bstr_t(sFilename), ios::binary);
if(!file) {
::AtlSetErrorInfo( GUID_NULL, L"Error opening file", 0, NULL, GUID_NULL, E_FAIL, 0 );
return E_FAIL; }
file.read(reinterpret_cast<char *>(pResult), sizeof(*pResult));
return S_OK;}

 

You might need to include atlcom.h or comdef.h in addition to the headers included by
the ATL assistant for this to work.

 

IOW VB strings are Unicode BSTR type strings. You will need a BSTR to C (char*) conversion routine. This is best done with a C/C++ wrapper function that calls your Fortran procedure. Note, Fortran knows nothing about NULL terminated C strings. Either pass the strlen of the string as an argument on the C side or search for the NULL character on the Fortran side.

 

Jim Dempsey

0 Kudos
FortranFan
Honored Contributor III
514 Views
0 Kudos
Steve_Lionel
Honored Contributor III
500 Views

There are two worked examples of passing strings from VB to Fortran in the compiler_f\MixedLanguage folder of the Samples Bundle. One uses the VB "by value" attribute to pass just the characters in a method compatible with Fortran character variables, the other demonstrates the use of BSTR strings and SafeArrays.

0 Kudos
Reply