2013-04-09 82 views
0

我试图控制MotorBee用C++, 的问题是,我使用的是与MotorBee“mtb.dll”MotorBee DLL和C++,内存访问冲突

我试图加载进来一个dll文件从DLL到我的C++程序的功能如下:

#include "stdafx.h" 
#include <iostream> 
#include "mt.h" 
#include "windows.h" 
using namespace std; 

HINSTANCE BeeHandle= LoadLibrary((LPCWSTR) "mtb.dll"); 
Type_InitMotoBee InitMotoBee; 
Type_SetMotors SetMotors; 
Type_Digital_IO Digital_IO; 

int main() { 
InitMotoBee = (Type_InitMotoBee)GetProcAddress(BeeHandle, " InitMotoBee"); 
SetMotors =(Type_SetMotors)GetProcAddress(BeeHandle, " SetMotors"); 
Digital_IO =(Type_Digital_IO)GetProcAddress(BeeHandle, " Digital_IO ");  InitMotoBee(); 
SetMotors(0, 50, 0, 0, 0, 0, 0, 0, 0); 
     system("pause"); 
return 0; 
} 

我收到一个错误说,我想读存储器, 0x00000000地址,当我尝试清点BeeHandle它显示为0x0地址(尝试检查处理值) 样本错误:

First-chance exception at 0x00000000 in 111111.exe: 0xC0000005: Access violation reading location 0x00000000. 
First-chance exception at 0x6148f2b4 in 111111.exe: 0xC0000005: Access violation reading location 0x00000000. 
First-chance exception at 0x6148f2b4 in 111111.exe: 0xC0000005: Access violation reading location 0x00000000. 
First-chance exception at 0x6148f2b4 in 111111.exe: 0xC0000005: Access violation reading location 0x00000000. 
First-chance exception at 0x6148f2b4 in 111111.exe: 0xC0000005: Access violation reading location 0x00000000. 

感谢你的帮助,

+2

执行'GetProcAddress的()'调用成功吗?我对此表示怀疑,因为用于函数名称的每个字符串文字都有空格。 – hmjd 2013-04-09 13:01:06

+0

如果'BeeHandle'为'0',表示DLL未成功加载。它与你的应用程序在同一个文件夹中吗? – 2013-04-09 13:02:06

+0

@hmjd正是..“访问冲突读取位置0x00000000”表示SetMotors为0.错误处理是件好事。 – stijn 2013-04-09 13:03:06

回答

2

这就让人不正确:

HINSTANCE BeeHandle= LoadLibrary((LPCWSTR) "mtb.dll"); 

,因为它铸造面值为宽字符串文字的字符串。只需使用一个宽字符串文字:

HINSTANCE BeeHandle = LoadLibrary(L"mtb.dll"); 
  • LoadLibrary()检查结果:尝试使用返回的函数指针之前的GetProcAddress()
  • 检查结果。在每个字符串文字中都有一个前导空格(还有一个尾随空格),用于指定函数名称,并将其删除。
  • 如果LoadLibrary()GetProcAddress()失败,请使用GetLastError()获取失败的原因。

代码摘要:

HINSTANCE BeeHandle = LoadLibrary(L"mtb.dll"); 
if (BeeHandle) 
{ 
    SetMotors = (Type_SetMotors)GetProcAddress(BeeHandle, "SetMotors"); 
    if (SetMotors) 
    { 
     // Use 'SetMotors'. 
    } 
    else 
    { 
     std::cerr << "Failed to locate SetMotors(): " << GetLastError() << "\n"; 
    } 
    FreeLibrary(BeeHandle); 
} 
else 
{ 
    std::cerr << "Failed to load mtb.dll: " << GetLastError() << "\n"; 
} 
+0

不是非法的,只是非常不合情理。 – john 2013-04-09 13:04:58

+0

@John,我会改变措辞。 – hmjd 2013-04-09 13:05:28

+0

编辑时,其中一个功能也有一个尾随空间。 – 2013-04-09 13:06:10