2013-04-09 95 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