我需要通过Visual Basic(VBWpf)从C++ Dll(BVRelate.dll)调用函数。如何从VB调用C++ DLL函数?
C++的dll代码:
//VBRelate.h
#ifdef VBRELATE_EXPORTS
#define VBRELATE_API __declspec(dllexport)
#else
#define VBRELATE_API __declspec(dllimport)
#endif
extern VBRELATE_API void DoSomething();
//VBRelate.cpp
#include <atlstr.h>
#include "VBRelate.h"
VBRELATE_API void DoSomething()
{
CString strOutput("Hello world");
MessageBox(NULL, strOutput, L"Got a message", MB_OK);
}
然后我尝试从VB(WPF项目)
Imports System.Runtime.InteropServices
Class MainWindow
Declare Function DoSomething Lib "M:\VBRelate.dll"()
Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
DoSomething()
End Sub
End Class
调用这个函数,而且我得到了一个例外:
“MarshalDirectiveException了未处理” 。类型 'System.Runtime.InteropServices.MarshalDirectiveException' 未处理的异常发生在VBWpf.exe
然后我用DUMPBIN:
dumpbin /exports "M:\VBRelate.dll">M:\VBRelate.txt
和VBRelate.txt是这样的:
Microsoft (R) COFF/PE Dumper Version 10.00.40219.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file M:\VBRelate.dll
File Type: DLL
Section contains the following exports for VBRelate.dll
00000000 characteristics
57E3DDA6 time date stamp Thu Sep 22 16:33:26 2016
0.00 version
1 ordinal base
1 number of functions
1 number of names
ordinal hint RVA name
1 0 00011299 [email protected]@YAXXZ = @ILT+660([email protected]@YAXXZ)
Summary
1000 .00cfg
4000 .data
1000 .gfids
1000 .idata
4000 .rdata
1000 .reloc
1000 .rsrc
10000 .text
10000 .textbss
1000 .tls
然后我试图使用def文件,但并不真正完全理解如何使用它(应该在哪里 - 与dll文件,项目文件或其他地方),为什么我应该在使用__declspec(而不是__stdcall)时使用它。所以我把DEF文件与DLL文件的目录,同时还与DLL文件的项目:
; VBRelate.def - defines the exports for VBRelate.dll
LIBRARY VBRelate.dll
DESCRIPTION 'A C++ dll that can be called from VB'
EXPORTS
DoSomething
然后我重建DLL。 它没有工作。同样的例外出现了。并且dumpbin返回了相同的转储,没有任何更改。
计划与选项严格了一会儿所以编译器?可以告诉你这样一个简单的错误。它是一个子,而不是一个功能。 –
我开启了这个选项,thanx。我试着声明函数DoSomething Lib“M:\ VBRelate.dll”()作为对象,并声明Sub DoSomething Lib“M:\ VBRelate.dll”()。同样的问题 –
在dll函数声明和定义中添加extern“C”使它工作。 –