3

I have a console app, myapp.exe. Within the app is a function, let's call it:

public static int AddIntegers(int a, int b)

Is it possible to make this function visible externally so that a VBscript could call it? Do I have to move the function into a DLL or can I leave it in the EXE and make it visible? If so, how?

FunLovinCoder
  • 7,597
  • 11
  • 46
  • 57

2 Answers2

4

Idealistically, you should be making a DLL and set Com Visible on the functions you need to expose.

using System;
using System.Runtime.InteropServices;
namespace MyDLL
{
   [ComVisible(true)]
   public class Operations
   {
       [ComVisible(true)]
       public int AddIntegers(int a, int b)
       {
           return a + b;
       }
    }
}

After you've compiled your DLL you need to register it with regasm.exe so that you can call it from VBScript:

Dim myObj
Set myObj = CreateObject("MyDLL.Operations")
Dim sum
sum = myObj.AddIntegers(3, 5)

This reply is based on the CodeProject posting How to call a .NET DLL from a VBScript by Raymund Macaalay. I recommend you read it.

Also, you should check other stackoverflow posting such as How to call C# DLL function from VBScript.

Community
  • 1
  • 1
Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
  • Many thanks. This is very useful. Are you saying it can't be called if it is in an EXE? Or are you saying it would be bad practice to do so and really I should move it out into a DLL? – FunLovinCoder Jan 26 '12 at 13:59
  • @FunLovinCoder there are scenarios where you can house a type library and its COM objects in an EXE. But, they're for non-VBScript scenarios. In your case, because you have both a console application and VBScript sharing functionality the usual scenario is to move the shared functionality to a DLL. That way, both the VBScript and your EXE are sharing the DLL, but, it isn't your VBScript calling your EXE. Alternatively, if you must run it this way, then, consider CreateObject("WScript.Shell") and calling Run() to invoke your EXE's Main and call your function through your command line arguments. – Stephen Quan Jan 26 '12 at 18:26
2

Yes, you will need to make the managed code library (DLL) visible to the VBScript (most likely through the GAC). Then in your VBScript, you can do something like:

dim yourObject = CreateObject("YourContainingObject");
yourObject.AddIntegers yourFirstInt, yourSecondInt