【问题标题】:MotorBee dll and c++, memory access violationMotorBee dll 和 c++,内存访问冲突
【发布时间】:2013-03-31 22:05:51
【问题描述】:

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

感谢您的帮助,

【问题讨论】:

  • GetProcAddress() 调用成功了吗?我对此表示怀疑,因为每个用于函数名称的字符串文字中的前导空格。
  • 如果BeeHandle0 则表示DLL 没有成功加载。它与您的应用程序在同一个文件夹中吗?
  • @hmjd 完全正确。“访问冲突读取位置 0x00000000”表示 SetMotors 为 0。错误处理是一件好事。
  • cout
  • 用 L 替换 (LPCWSTR) 会出现错误:L undeclared identifier

标签: c++ dll


【解决方案1】:

这个演员表不正确:

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

因为它将字符串文字转换为宽字符串文字。只需使用宽字符串文字:

HINSTANCE BeeHandle = LoadLibrary(L"mtb.dll");
  • LoadLibrary()的检查结果:
  • 在尝试使用返回的函数指针之前检查GetProcAddress() 的结果。每个字符串文字中都有一个前导空格(还有一个尾随空格,这要归功于 cmets 中的 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";
}

【讨论】:

  • 实际上并不违法,只是非常不可取。
  • @John,我会改一下措辞。
  • 在编辑时,其中一个函数也有一个尾随空格。
  • 用 L 替换 (LPCWSTR) 会报错:L undeclared identifier
  • std::cerr
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
  • 1970-01-01
  • 2012-05-22
相关资源
最近更新 更多