Accessing public variables from a c++ program

60 Views Asked by At

I have a program written in VB2012 and I'm trying to do the heavy number crunching in a c++ DLL. There are lots of variables that the c++ program needs access to. What I would like to do it pass a Class object into the DLL (lets call it Class_fred) and the variables through the class.

VB code

class class_fred
   public var_1 = 10
   public var_2 = 20

   heavyLifter (&class_fred)

end class

C++ code

void heavyLifter (object* cf) {
  int a, b;
  a = cf->var_1 + cf->var_2;
}
1

There are 1 best solutions below

0
Étienne Laneville On

In your VB.NET project, you'll want to add a reference to your C++ DLL. This can be done from the Solution Explorer in your project. Then, in your code, you can access it by passing it to your Fred objects. This code is a general example on how it can be done, using HeavyDotNetClass as your Fred class and HeavyLifting as the name of the COM assembly:

Imports HeavyLifting

Public Class HeavyDotNetClass
    Implements HeavyLifting.IHeavyObject

    Private _lifter As HeavyLifting.HeavyLifter
    Private _var1 As Integer = 10
    Private _var2 As Integer = 20

    Public Sub New(lifter As HeavyLifting.HeavyLifter)
        _lifter = lifter
    End Sub

    Public Property Var1 As Integer Implements _IHeavyObject.Var1
        Get
            Return _var1
        End Get
        Set(value As Integer)
            _var1 = value
        End Set
    End Property

    Public Property Var2 As Integer Implements _IHeavyObject.Var2
        Get
            Return _var2
        End Get
        Set(value As Integer)
            _var2 = value
        End Set
    End Property

    Public Sub Lift()
        If _lifter IsNot Nothing Then
            _lifter.Process(Me)
        End If

    End Sub

End Class

In your C++ DLL (imported as HeavyLifting here) you should define an Interface (HeavyLifting.IHeavyObject) that Class Fred will implement. In this example, the IHeavyObject interface has two properties, Var1 and Var2.

You would then create an instance of your C++ object and pass it to an instance of HeavyDotNetClass:

Dim heavyLifter As New HeavyLifting.HeavyLifter
Dim heavyObject As New HeavyDotNetClass(heavyLifter)

heavyObject.Lift()

In this example, the C++ object would have a method called Process with a parameter of type IHeavyObject.