我正在尝试从vb.net获取DllExport到非托管c ++工作。
我在Visual Studio 2012中使用Robert Giesecke's Unmanaged Exports并试图遵循此very helpful hints。我通过在* .cpp和* .h文件所在的目录中的后期构建操作来复制.Net项目中的dll。
我用dumpbin /EXPORTS Nugget.Discovery.dll
检查了我的dll,它告诉我有导出:
File Type: DLL
Section contains the following exports for \Nugget.Discovery.dll
00000000 characteristics
52554A05 time date stamp Wed Oct 09 14:20:21 2013
0.00 version
0 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
0 0 0000532E StartAnnouncing
1 1 0000533E StopAnnouncing
Summary
2000 .reloc
4000 .rsrc
2000 .sdata
4000 .text
但是如果我尝试使用
在cpp文件中导入它#import "Nugget.Discovery.dll"
void StartAnnouncing(int serial);
我尝试编译后出现一个IntelliSense错误和一个错误:
IntelliSense: cannot open source file "Debug/Nugget.Discovery.tlh"
error C1083: Cannot open type library file: 'nugget.discovery.dll': Fehler beim Laden der Typbibliothek/DLL.
知道我做错了吗?
祝你好运! 斯蒂芬
答案 0 :(得分:3)
作为DllExport的一部分,会生成.lib文件。您可以使用它来使用普通的C ++链接器而不是LoadLibrary / GetProcAddress。
从您发布的托管代码开始,在本机端:
extern CALLBACK void StartAnnouncingType(int serial);
extern CALLBACK int TestType(void);
int _tmain(int argc, _TCHAR* argv[])
{
int test = TestPtr();
StartAnnouncingPtr(1);
}
在您的非托管项目的设置中,将Nugget.Discovery.lib
添加到项目属性:Configuration Properties-> Linker-> Input。并将Nugget.Discovery.dll复制到输出目录。
答案 1 :(得分:2)
好的,感谢Hans Passant我来到了这个解决方案:
这是我在管理方面的代码:
Imports System.Runtime.InteropServices
Imports RGiesecke.DllExport
Public NotInheritable Class Beacon
Private Sub New()
End Sub
Private Shared _nuggetAnnouncement As NuggetAnnouncement
' ReSharper disable UnusedMember.Local
''' <remarks>Cannot be called from managed code!</remarks>
<DllExport("StartAnnouncing", CallingConvention.StdCall)>
Private Shared Sub StartAnnouncingNative(serial As Integer)
StartAnnouncing(serial)
End Sub
''' <remarks>Cannot be called from managed code!</remarks>
<DllExport("Test", CallingConvention.StdCall)>
Private Shared Function TestNative() As Integer
Return Test()
End Function
' ReSharper restore UnusedMember.Local
Public Shared Sub StartAnnouncing(serial As Integer)
'do something
End Sub
Public Shared Function Test() As Integer
Return 42
End Function
End Class
有趣的是,我无法从托管代码中调用标有<DllExport>
的函数(即使它们是公共的)。
这是本机代码:
typedef void (CALLBACK* StartAnnouncingType)(int);
typedef int (CALLBACK* TestType)(void);
int _tmain(int argc, _TCHAR* argv[])
{
HINSTANCE dllHandle = NULL;
StartAnnouncingType StartAnnouncingPtr = NULL;
TestType TestPtr = NULL;
wchar_t dllNameWide[64];
int size = mbstowcs(dllNameWide, "Nugget.Discovery.dll", sizeof(dllNameWide));
dllHandle = LoadLibrary(dllNameWide);
if (NULL != dllHandle)
{
//Get pointer to our function using GetProcAddress:
StartAnnouncingPtr = (StartAnnouncingType)GetProcAddress(dllHandle,"StartAnnouncing");
TestPtr = (TestType)GetProcAddress(dllHandle,"Test");
int test;
if (NULL != TestPtr) test = TestPtr();
int serial = 1;
if (NULL != StartAnnouncingPtr) StartAnnouncingPtr(1);
//Free the library:
FreeLibrary(dllHandle);
}
}
还有其他更好的解决方案吗?
侨! 斯蒂芬