[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3236
  • Last Modified:

Calling VB.NET dll from C++ dll

Im having a very hard time finding anything that can either how to do this or if it is even possible - I want to call a VB.NET dll from within a plain old C++ dll (not .NET!).

I have a sneaking suspicion it simply cant be done.

Ive read a bit about managed and unmanaged code and I think this is where the problem is.
0
MrNed
Asked:
MrNed
  • 3
  • 2
1 Solution
 
vascovCommented:
One option is to use COM Interop.

Export your types into a typelib. Then use #import to import the types. No need for Managed extensions.

HTH
0
 
vascovCommented:
Here's a sample:

VB.NET Lib:
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices

<Assembly: AssemblyKeyFile( "mykey.snk" )>

< ComVisible( true ) > _
Public Interface IAClass
      Function GetCurrentTime() As String
End Interface

< ProgId( "MyCompany.MyLib.AClass" ) > _
Public Class AClass
      Implements IAClass

      Public Function GetCurrentTime() As String Implements IAClass.GetCurrentTime
            Return System.DateTime.Now.ToString()
      End Function
End Class

To compile the MyLib.vb file:
sn -k mykey.snk
vbc /t:library MyLib.vb

Then to "deploy" (register it with COM to make it available for import in C++)
regasm /tlb:MyLib.tlb MyLib.dll
gacutil -i MyLib.dll

(1st we register it in the COM registry, and ask for a .tlb file to use with our Cpp code)
(2nd we make the Assembly global so that any instantiation can find it)


Now onto our Cpp code:
#include <windows.h>
#include <atlbase.h>
#include <stdio.h>

#import "./Mylib.tlb"  // import the tlb we generated previously

int main()
{
      /* DEMO CODE - NO ERROR HANDLING */
      CoInitialize( 0 );   // Initialize COM
      {
            using namespace MyLib;    // save us from the trouble of always doing MyLib::IAClass, etc...

            CComPtr< IAClass > pIAClass;
            pIAClass.CoCreateInstance( __uuidof( AClass ) );   // Create the object

            _bstr_t bstrResult = pIAClass->GetCurrentTime();  // Call our .NET func and get the result

            printf( "Current DateTime: %s\n", (char*)bstrResult );
      }
      CoUninitialize();
}

compiling this is trivial:
cl MyApp.cpp

HTH
0
 
MrNedAuthor Commented:
Thanks!!!!

I actually understand very little of that, but I'll have a play and see what I can come up with.
0
 
vascovCommented:
Let me know of your progress...

If you have a specific situation you want to address, you're welcomed.

Thx
0
 
MrNedAuthor Commented:
Thanks for your help. We got it working based on what you provided.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now