MotorBee dll和c ++,内存访问冲突

时间:2013-04-09 12:57:59

标签: c++ dll

我正在尝试使用c ++控制MotorBee, 问题是我使用的是随MotorBee附带的dll文件" mtb.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, 当我尝试cout 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.

谢谢你的帮助,

1 个答案:

答案 0 :(得分:2)

此演员表不正确:

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

将字符串文字强制转换为宽字符串文字。只需使用宽字符串文字:

HINSTANCE BeeHandle = LoadLibrary(L"mtb.dll");
  • 检查LoadLibrary()的结果:
  • 在尝试使用返回的函数指针之前检查GetProcAddress()的结果。每个字符串文字中都有一个前导空格(还有一个尾随空格,感谢评论中的Roger),用于指定函数名称,删除它们。
  • 如果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";
}