我正在嘗試與使用CAN的設備進行通信。爲此,我使用C++使用PCAN Basic。如何訪問C++中的dll文件中的函數
不幸的是,我對dll文件(這是提供的)訪問函數一無所知。我發現這個鏈接:
Calling a dll function from C++
,我試圖通過代碼使用調用LoadLibrary我發現這裏:
http://www.goffconcepts.com/techarticles/development/cpp/calldll.html
我的代碼:
// dll_get_func.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h> /* For sqrt() */
#include <windows.h>
#define DELCLDIR __declspec("Pcan_usb.dll")
#define PCAN_USBBUS1 0x51
#define CAN_BAUD_1M 0x0014 // 1 MBit/s
#define MSGTYPE_STANDARD 0x00
typedef struct {
DWORD ID; // 11/29 bit identifier
BYTE MSGTYPE; // Bits from MSGTYPE_*
BYTE LEN; // Data Length Code of the Msg (0..8)
BYTE DATA[8]; // Data 0 .. 7
} TPCANMsg;
int hardCodeInit(void)
{
/* get handle to dll */
HINSTANCE hGetProcIDDLL = LoadLibrary(_T("Pcan_usb.dll"));
/* get pointer to the function in the dll*/
FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"CAN_Init");
/*
Define the Function in the DLL for reuse. This is just prototyping the dll's function.
A mock of it. Use "stdcall" for maximum compatibility.
*/
typedef int (__stdcall * pICFUNC)(WORD wBTR0BTR1, int CANMsgType);
pICFUNC CAN_Init;
CAN_Init = pICFUNC(lpfnGetProcessID);
//DWORD __stdcall CAN_Init(WORD wBTR0BTR1, int CANMsgType);
/* The actual call to the function contained in the dll */
int intMyReturnVal = CAN_Init(PCAN_USBBUS1,CAN_BAUD_1M);
/* Release the Dll */
FreeLibrary(hGetProcIDDLL);
/* The return val from the dll */
return intMyReturnVal;
}
int hardCodeWrite(void)
{
HINSTANCE hGetProcIDDLL = LoadLibrary(_T("Pcan_usb.dll"));
FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"CAN_Write");
typedef int (__stdcall * pICFUNC)(WORD wBTR0BTR1, TPCANMsg CANMsgType);
pICFUNC CAN_Write;
CAN_Write = pICFUNC(lpfnGetProcessID);
TPCANMsg msgOut;
msgOut.MSGTYPE = MSGTYPE_STANDARD;
msgOut.LEN = 1;
msgOut.DATA[0] = 0x03; // 0x03 = Get ID
int toReturn;
toReturn = CAN_Write(PCAN_USBBUS1,msgOut);
FreeLibrary(hGetProcIDDLL);
return toReturn;
}
int _tmain(int argc, _TCHAR* argv[])
{
int derp=hardCodeInit();
int herp=hardCodeWrite();
std::cout<<derp;
std::cout<<herp;
_getch();
return 0;
}
但是,Visual Studio中說:有一個:
Unhandled exception at 0x10001D95 (Pcan_usb.dll) in dll_get_func.exe: 0xC0000005:
Access violation reading location 0x00000051.
我有Pcan_usb.dll和Pcan_usb.lib在同一個文件夾中,我使用的Visual Studio 2012
檢查'LoadLibrary'和'GetProcAddress'的返回值。如果他們失敗了'GetLastError'說什麼? –
DLL是否帶有鏈接庫文件和頭文件?然後包含頭文件並鏈接到庫中,而不必自己加載DLL或擔心函數指針。 –
@ JoachimPileborg-好點,我仔細看了看,有一個.h文件。我包含了.h文件。它現在給我'錯誤錯誤LNK2019:無法解析的外部符號_CAN_Init @ 8在函數中引用_wmain \t C:\ Users \ britter \ Documents \ Visual Studio 2012 \ Projects \ dll_get_func \ dll_get_func \ dll_get_func.obj \t dll_get_func'這是猜測是一個圖書館沒有得到解決。您提到的「鏈接庫」是我需要添加的一行代碼,或者需要在Visual Studio項目中配置的選項? (如果這是脫節主題,我應該提交一個新的問題/編輯嗎?) – code11