How to call VB.NET DLL from C++ (Call the functions also - not DLL file only)

橙三吉。 提交于 2019-12-01 01:01:26

Since your vb assembly needs a totally different runtime than the 'native' executable, you will need to use some layer in between. This layer may be COM.

You can expose your assembly to the COM subsystem by it's 'ComVisible' property. Then, you should register the assembly to expose it to COM 'subscribers'.

Only then you can #import the assembly namespace from your c++ code.

Note: this is a very brief version of an msdn article "How to call a managed DLL from native Visual C++ code"

EDIT-- Just tried it out... and it seems to work allright:

C# code

namespace Adder
{
    public interface IAdder
    {
        double add(double a1, double a2);
    }
    public class Adder : IAdder
    {
        public Adder() { }
        public double add(double a1, double a2) { return a1 + a2; }
    }
}

Project settings

[assembly: ComVisible(true)]
[assembly: AssemblyDelaySign(false)]

(Signing was needed in order to be able to generate the tlb)

C++ code:

#import <adder.tlb> raw_interfaces_only

  CoInitialize(NULL);
  Adder::IAdderPtr a;
  a.CreateInstance( __uuidof( Adder::Adder ) );
  double d = 0;
  a->add(1.,1., &d); 
  // note: the method will return a HRESULT; 
  // the output is stored in a reference variable.
  CoUninitialize();
  • GetProcAddress does not understand C++ name mangling, not to mention any other mangling, so there is no dll for which "Class1::example_function1" could be valid identifier. Normally it's only used with extern "C" (or implemented in C without ++) functions, which are not mangled.
  • If it's implemented in VB.NET, it's not a dll at all. It's a .net assembly and you need to be running in CLR (.net runtime) to use it. You can run C++ code in CLR, but it has to be the "Managed C++", which is extended with special types for .net object references and operation with the garbage collector.

You can't directly access .NET code from native C++, you will need C++/CLI for that.

If your program needs to be native C++, there is the possibility of writing a mixed-mode wrapper DLL which provides a native C++ interface for the main program, and uses C++/CLI in the implementation to forward calls to the .NET DLL.

You would need to write a wrapper on C++/CLI for that . You might find the following link helpful. http://www.codeproject.com/KB/mcpp/cppcliintro01.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!