问题描述
我按照以下页面上的教程创建了一个 C++ DLL,并将其放在 System32 文件夹中:http://msdn.microsoft.com/en-us/library/ms235636%28v=vs.80%29.aspx.我可以从 PC 上的任何地方运行 .exe.现在我希望能够从 VB.NET 应用程序调用 Add,所以我添加了以下代码:
I have followed the tutorial on the following page to create a c++ DLL and I have put it in the System32 folder: http://msdn.microsoft.com/en-us/library/ms235636%28v=vs.80%29.aspx. I am able to run the .exe from anywhere on the PC. Now I want to be able to call Add from a VB.NET application, so I have added the following code:
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim Test As Integer
Test = Add(1, 1)
MsgBox(Test)
Catch ex As Exception
End Try
End Sub
<DllImport("MathFuncsDll.dll", EntryPoint:="Add", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Private Shared Function Add(ByVal a As Double, ByVal B As Double) As Double
End Function
End Class
我收到以下错误:无法在 DLLMathFuncsDll.dll"中找到名为Add"的入口点.我相信这是因为命名空间.我对此进行了研究,有些网页说平台调用不允许使用命名空间,有些网页说允许使用.有什么问题?
I get the following error: Unable to find an entry point named 'Add' in DLL 'MathFuncsDll.dll. I believe this is because of the namespace. I have researched this and some web pages say namespaces are not allowed with Platform Invoke and some web pages say they are allowed. What is the problem?
推荐答案
入口点未命名为添加".从 Visual Studio 命令提示符运行 dumpbin/exports MathFuncsDll.dll
以查看导出的名称.要获得此声明:
The entry point is not named "Add". From the Visual Studio Command Prompt, run dumpbin /exports MathFuncsDll.dll
to see the exported names. To get this declaration:
<DllImport("MathFuncsDll.dll", EntryPoint:="?Add@MyMathFuncs@MathFuncs@@SANNN@Z", _
CallingConvention:=CallingConvention.Cdecl)> _
Private Shared Function Add(ByVal a As Double, ByVal B As Double) As Double
End Function
奇怪的名字是由C++编译器产生的,一个叫做名字修饰"的特性.它支持函数重载.您可以将 extern "C"
放在函数声明的前面以抑制它.如果你不这样做实际上更好.还要注意 SetLastError 不正确,代码实际上并没有调用 SetLastError() 来报告错误.而 CharSet 不合适,这些函数不接受字符串.
The strange looking name is produced by the C++ compiler, a feature called "name decoration". It supports function overloading. You can put extern "C"
in front of the function declaration to suppress it. It is actually better if you don't. Also note that SetLastError wasn't correct, the code doesn't actually call SetLastError() to report errors. And CharSet wasn't appropriate, these functions don't take strings.
您还需要对 Divide 函数做一些事情,在互操作场景中抛出 C++ 异常不会有好结果,只有 C++ 代码才能捕获异常.
You'll also need to do something about the Divide function, throwing a C++ exception won't come to a good end in an interop scenario, only C++ code can catch the exception.
这篇关于Visual C++ 托管应用程序:无法找到名为“添加"的入口点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!