如何从C ++调用VB.NET DLL(也调用函数 – 不是DLL文件)

我想问一下如何从C ++程序调用VB.NET DLL的问题

我已经多次尝试从C ++调用VB.NET DLL文件,它工作正常,但问题是我无法调用VB.NET DLL文件的function(我只能加载VB.NET DLL文件)

在VB.NET DLL中我有以下代码:

Public Function example_function1(ByVal i As Integer) As Integer Return 3 End Function Public Function example_function2(ByVal i As Integer) As Integer Return 3 End Function 

============================

我的C ++代码是:

  typedef int (__stdcall *ptf_test_func_1_type)(int); typedef int (__stdcall *ptf_test_func_2_type)(int*); int i =1; HINSTANCE dll_instance = LoadLibrary("DLLs7.dll"); int main() { if(dll_instance !=NULL) { printf("The DLLs file has been Loaded \n"); cout << GetLastError() << endl; ptf_test_func_1_type p_func1=(ptf_test_func_1_type)GetProcAddress(dll_instance,"Class1::example_function1"); ptf_test_func_2_type p_func2=(ptf_test_func_2_type)GetProcAddress(dll_instance,"Class1::example_function2"); // Function No 1 // if (p_func1 != NULL) { cout << "\nThe function number 1 is " << p_func1(i) << endl; } else { cout << "\nFailed" << endl; cout << GetLastError() << endl; } // Function No 2 // if (p_func2 != NULL) { cout << "\nThe function number 2 is" << p_func2(&i) << endl; } else { cout << "\nFailed" << endl; cout << GetLastError() << endl; } } else { printf("\nDLLs file Load Error"); cout << GetLastError() << endl; } cout << GetLastError() << endl; return(0); } 

我的以下步骤是:

1)我创建了VB.NET DLL。

2)我创建了一个新的应用程序visual C ++并选择了“win32控制台应用程序”

3)我编写了代码来调用DLL和函数(如上所示)

我没有错过任何步骤或代码,因为我可以调用VB.NET DLL文件,但我不能调用VB.NET DLL函数

你可以看到我写了GETLASTERRIR()来找到错误

cout << GetLastError()<< endl;

但是我在失败时发现了错误127,在调用DLL文件中发现了203

谁能帮我

非常感谢你

问候

由于您的vb程序集需要与“本机”可执行文件完全不同的运行时,因此您需要在它们之间使用一些层。 该层可以是COM。

您可以通过它的“ComVisible”属性将程序集公开给COM子系统。 然后,您应该注册程序集以将其公开给COM’订阅者’。

只有这样你才能从你的c ++代码#import程序集命名空间。

注意:这是msdn文章“ 如何从本机Visual C ++代码调用托管DLL ”的一个非常简短的版本

编辑 – 刚试了一下……似乎工作正常:

C#代码

 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; } } } 

项目设置

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

(需要签名才能生成tlb)

C ++代码:

 #import  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不理解C ++名称修改,更不用说任何其他修改,因此没有"Class1::example_function1"可能是有效标识符的DLL。 通常它只用于extern "C" (或在没有++的C中实现)函数,它们没有被破坏。
  • 如果它是在VB.NET中实现的, 那根本就不是一个dll 。 它是一个.net程序集,您需要在CLR(.net运行时)中运行才能使用它。 您可以在CLR中运行C ++代码,但它必须是“托管C ++”,它使用.net对象引用的特殊类型进行扩展,并使用垃圾收集器进行操作。

您不能直接从本机C ++访问.NET代码,您将需要C ++ / CLI。

如果您的程序需要是本机C ++,则可以编写混合模式包装DLL,为主程序提供本机C ++接口,并在实现中使用C ++ / CLI将调用转发到.NET DLL。

您需要在C ++ / CLI上编写一个包装器。 您可能会发现以下链接很有用。 http://www.codeproject.com/KB/mcpp/cppcliintro01.aspx