How to get file information? - c++

I have an existing file on the computer and I was wondering if it is possible to know when it was made, Size of the file, and more properties on the file..
I tried to use in ifstream But there's the information I have on file
(I'm using Visual C++ 6.0,Cannot using Boost)

Look at function GetFileAttributesEx.
#include <windows.h>
WIN32_FILE_ATTRIBUTE_DATA fInfo;
GetFileAttributesEx("test.dat", GetFileExInfoStandard, &fInfo);
The WIN32_FILE_ATTRIBUTE_DATA contains a lot of the "common" file informations (size, creation/edit time, attributes).
Update: I just saw, that you're using Visual C++ 6. Since GetFileAttributesEx is supported since Windows XP it might not be available in your WIN API headers... You can use the function by dynamic linking. The following code does the same thing as the snippet from above:
/* clone definition of WIN32_FILE_ATTRIBUTE_DATA from WINAPI header */
typedef struct file_info_struct
{
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
} FILE_INFO;
/* function pointer to GetFileAttributesEx */
typedef BOOL (WINAPI *GET_FILE_ATTRIBUTES_EX)(LPCWSTR lpFileName, int fInfoLevelId, LPVOID lpFileInformation);
HMODULE hLib;
GET_FILE_ATTRIBUTES_EX func;
FILE_INFO fInfo;
hLib = LoadLibrary("Kernel32.dll");
if (hLib != NULL)
{
func = (GET_FILE_ATTRIBUTES_EX)GetProcAddress(hLib, "GetFileAttributesExW");
if (func != NULL)
{
func("test.dat", 0, &fInfo);
}
FreeLibrary(hLib);
/*
** Don't call func after FreeLibrary !!!
** It should be ok since kernel32.dll is loaded by your application anyway but if
** you get a function pointer from a dll only loaded by LoadLibrary the function
** pointer is invalid once the library if freed.
*/
}

The size and creation data (and more) are available via FindFirstFile.

Related

Why does LoadLibrary fail whilst LoadLibraryA succeeds in loading a DLL? [duplicate]

This question already has answers here:
Cast to LPCWSTR?
(4 answers)
Closed 3 years ago.
I'm trying to load a DLL into C++ but was getting error code 126, which I think means the DLL couldn't be found. After some poking around I changed LoadLibrary to LoadLibraryA and suddendly it worked. However, I am at a complete loss as to why. I realise that I haven't provided the dll for this code to be runable but would be greatful if somebody could provide an explaination as to why this is happening? And prehaps an example of how to get LoadLibary working.
Broken version
#include <stdio.h>
#include <windows.h>
typedef char* (*gf_getCurrentLibraryVersion) ();
int main() {
gf_getCurrentLibraryVersion getVersion;
HINSTANCE hLib = LoadLibrary((LPCWSTR)"libsbnw.dll");
if (hLib) {
getVersion = (gf_getCurrentLibraryVersion)GetProcAddress(hLib, "gf_getCurrentLibraryVersion");
printf("Version = %s\n", getVersion());
}
else {
printf("Error loading dll: %d/n", GetLastError());
}
printf("Hit any key to continue\n");
getchar();
return 0;
}
Compiles and outputs
Error loading dll: 126/nHit any key to continue
to console
Working version
#include <stdio.h>
#include <windows.h>
typedef char* (*gf_getCurrentLibraryVersion) ();
int main() {
gf_getCurrentLibraryVersion getVersion;
HINSTANCE hLib = LoadLibraryA("libsbnw.dll");
if (hLib) {
getVersion = (gf_getCurrentLibraryVersion)GetProcAddress(hLib, "gf_getCurrentLibraryVersion");
printf("Version = %s\n", getVersion());
}
else {
printf("Error loading dll: %d/n", GetLastError());
}
printf("Hit any key to continue\n");
getchar();
return 0;
}
Compiles and outputs
version is: 1.3.4
The problem with your LoadLibrary((LPCWSTR)"libsbnw.dll") call is that your build environment converts that to a LoadLibraryW call, but the way you are trying to pass a wide-character string is wrong.
As you have it, you are simply casting a const char* pointer to a const wchar_t* pointer, which won't work (for example, it will interpret the initial "li" characters as a single 16-bit character).
What you need to do is specify the string literal as a wide character constant, using the L prefix:
HINSTANCE hLib = LoadLibrary(L"libsbnw.dll");
Or, alternatively, using the TEXT() macro (which will boil down to the same, when using the UNICODE build environment):
HINSTANCE hLib = LoadLibrary(TEXT("libsbnw.dll"));
Feel free to ask for further explanation and/or clarification.
Ordinarily the compiler will try to point out when you're making a mistake. But in this case you've told it not to by adding an explicit cast to the string.
HINSTANCE hLib = LoadLibrary((LPCWSTR)"libsbnw.dll");
//^^^^^^^^^
I'm assuming you've built your app with Unicode enabled, which defines a macro converting LoadLibrary to LoadLibraryW. The parameter must be a wide-character string.
HINSTANCE hLib = LoadLibraryW(L"libsbnw.dll");
There's another macro you can use when you're not sure if the app will be compiled with Unicode or not, TEXT() or the shorter form _T(). Not recommended for modern code since needing to turn Unicode on or off hasn't been a problem in many years, just use Unicode always.
HINSTANCE hLib = LoadLibrary(TEXT("libsbnw.dll"));

How to redefine c++ pointer function?

I have code from BASS lib.
#ifndef BASSDEF
#define BASSDEF(f) WINAPI f
#else
#define NOBASSOVERLOADS
#endif
HSAMPLE BASSDEF(BASS_SampleLoad)(BOOL mem, const void *file, QWORD offset, DWORD length, DWORD max, DWORD flags);
I need redefine BASSDEF to call dlsym function. How can i do this?
Update:
I using this on Android NDK (Linux) i loaded bass module via function dlopen and i need to make all functions point (here is original header file of bass lib https://pastebin.com/Z2Ty9UsY ) to this loaded module via dlsym function. I need this to call all functions (from JNI inside bass.so) module easily.
Actually, BASSDEF is not a function. It's macro which is known at compile time. So let's unwrap it ourselves:
HSAMPLE WINAPI BASS_SampleLoad(BOOL mem, const void *file, QWORD offset, DWORD length, DWORD max, DWORD flags);
Whoa, just function declaration here. Now "WINAPI" is basicly __stdcall call convention (Microsoft-specific). But, looking to BASS header you provided one can find for non-WIN32 systems:
#define WINAPI
Basicly, under Linux it's just a placeholder which expands to nothing. Now function declaration looks like this:
HSAMPLE BASS_SampleLoad(BOOL mem, const void *file, QWORD offset, DWORD length, DWORD max, DWORD flags);
What's next? You would like to find this function in some shared library via dlsym?
I assume you wants something like this:
// Declare a function pointer in C++11 style
using BASS_SampleLoad_FuncPtr = std::add_pointer<decltype(BASS_SampleLoad)>::type;
// Open library you wants
void* soHandle = dlopen("your_lib_here.so", RTLD_LAZY);
// Error check!
if (nullptr == soHandle) {
// Fail here
}
// Finally, get pointe to function!
BASS_SampleLoad_FuncPtr BASS_SampleLoad = reinterpret_cast<BASS_SampleLoad_FuncPtr>(dlsym(soHandle, "BASS_SampleLoad"));
// Error check!
if (nullptr == BASS_SampleLoad) {
// Fail here
}
// Now only here it's safe to call "BASS_SampleLoad" with required params
auto sample = BASS_SampleLoad(...);
...
// Don't forget to close lib
dlclose(soHandle);
Please, NOTE!
Provided code is not tested and might contain errors. And, it's C++11 standard.
Also, for C++14 and higher replace 'std::add_pointer<...>::type' with 'std::add_pointer_t<...>'
P.S. this code valid because BASS is cross-platform library and all WinAPI-look-a-like stuff (WINAPI, QWORD, BOOL, DWORD, etc.) is defined for Linux in BASS header

Access violation when invoking a C++ DLL from Delphi

I write a Unicode DLL in Visual C++ 6.0. Then try to invoke the DLL function from Delphi XE3.
When I debug in Delphi, when step over the line to invoke the DLL function, I will always get an Access violation exception.
However, when I debug in Visual C++, I can see all parameters passed from Delphi are correct and I can step over all codelines without any exceptions.
If running outside the debugger, then I will not see any "access violation exceptions.
I try many methods but still cannot figure out how to eliminate the exception when debuggin in Delphi.
Below is the code in Visual C++ 6.0 part:
TestDLL.cpp:
extern "C" VOID WINAPI Test(CONST MESSAGEPROC lpMessageProc, LPVOID lParam)
{
if (lpMessageProc != NULL)
(*lpMessageProc)(1500, (const LPVOID)(LPCTSTR)CString((LPCSTR)IDS_MYTEST), lParam);
/*
if (lpMessageProc != NULL)
(*lpMessageProc)(1500, (const LPVOID)(LPCTSTR)CString(_T("Test")), lParam);*/
}
TestDLL.h:
// TestDLL.h : main header file for the TESTDLL DLL
//
#if !defined(AFX_TESTDLL_H__38054A53_5CEE_4ABF_9BA8_BCE427FCB8E1__INCLUDED_)
#define AFX_TESTDLL_H__38054A53_5CEE_4ABF_9BA8_BCE427FCB8E1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef BOOL (CALLBACK* MESSAGEPROC)(CONST DWORD dwMessageId, CONST LPVOID lp, LPVOID lParam);
VOID WINAPI Test(CONST MESSAGEPROC lpMessageProc, LPVOID lParam);
#ifdef __cplusplus
}
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TESTDLL_H__38054A53_5CEE_4ABF_9BA8_BCE427FCB8E1__INCLUDED_)
Below is the codes in Delphi XE3 part:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
public
{ Public declarations }
end;
PForm1 = ^TForm1;
TMessageProc = function (const dwMessageId: DWORD; const lp: Pointer; lParam: Pointer): BOOL; stdcall;
{$EXTERNALSYM TMessageProc}
var
Form1: TForm1;
procedure Test(const lpMessageProc: TMessageProc; lParam: Pointer); stdcall;
implementation
{$R *.dfm}
procedure Test; external 'TestDLL.dll' index 2;
function MessageProc(const dwMessageId: DWORD; const lp: Pointer; lParam: Pointer): BOOL; stdcall;
begin
Result := True;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Test(MessageProc, #Self); // <---- This code line will cause "access violation
end;
I belive the problem occurs in DLL test function, when it try to load string from resource using CString((LPCSTR)IDS_MYTEST). If I change the code to CString(_T("Test")), then problem disappears.
Thanks
As you surmised, this statement will not work:
CString((LPCSTR)IDS_MYTEST)
Although this constructor of CString does allow you to pass it a resource ID, it will try to find the resource in the calling process's (ie, the Delphi EXE's) resources, not in the DLL's resources. You need to use the HINSTANCE of the DLL, as provided by the DLL's DllMain(), when loading strings from the DLL's resources. You can use the CString::LoadString() method for that, eg:
HINSTANCE hInst;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
hInst = hinstDLL;
return TRUE;
}
extern "C" VOID WINAPI Test(CONST MESSAGEPROC lpMessageProc, LPVOID lParam)
{
if (lpMessageProc != NULL)
{
CString str;
str.LoadString(hInst, IDS_MYTEST);
(*lpMessageProc)(1500, (LPCTSTR)str, lParam);
}
}
I finally figure out this is a bug of MFC codes(VC6.0 version).
I don't know if I can post MFC source codes so I will just paste the function headers and related parts only.
In Microsoft Visual Studio\VC98\MFC\SRC\STRCORE.CPP, we can see the following 3 functions:
//////////////////////////////////////////////////////////////////////////////
// More sophisticated construction
CString::CString(LPCTSTR lpsz) // Function 1
{
Init();
if (lpsz != NULL && HIWORD(lpsz) == NULL)
{
UINT nID = LOWORD((DWORD)lpsz);
if (!LoadString(nID))
TRACE1("Warning: implicit LoadString(%u) failed\n", nID);
}
else
{
// Construct string normally
}
}
/////////////////////////////////////////////////////////////////////////////
// Special conversion constructors
#ifdef _UNICODE
CString::CString(LPCSTR lpsz) // Function 2
{
// Construct string normally
}
#else //_UNICODE
CString::CString(LPCWSTR lpsz) // Function 3
{
// Construct string normally
}
#endif //!_UNICODE
As we can see in the above code snippet, only function 1 contains codes that will take special process on lpsz and check if it is a string resource ID, if yes, then load the string from the resource. Both function 2 & 3 have no such special processes.
When we create a project in VS6, the default settings for a project is _MBCS, in such a case, function 1 will become
CString::CString(LPCSTR lpsz)
so CString((LPCSTR)nResID) will actually invoke function 1 and load string resource properly.
Function 2 will be disabled since _UNICODE is not defined. And function 3 works with wide char strings.
Therefore, for _MBCS project, everything works perfectly and consistently with the MSDN document.
However, when I change _MBCS to _UNICODE, function 1 will become
CString::CString(LPCWSTR lpsz)
Fucntion 2 will be enabled and function 3 will be disabled.
So CString((LPCSTR)nResID) will actually invoke function 2, which does NOT have special process to load string resource, which makes the problem.
There are two solutions for this problem:
Always use CString((LPCTSTR)nResID) instead of CString((LPCSTR)nResID) to load a string from resource. However, this usage is inconsistent with MSDN document so we have to call it as an undocumented usage.
Always use LoadString to load a string resource.
Though solution 1 is a little simpler, it is an undocumented usage so I finally opt solution 2 to solve my problem.
Many thanks to all your helps in solving this issue.

Calling Win32 DLL from C++

I am new to the DLL world. I have been given a Win32 DLL which has a lot of functions. Need to call these DLL functions from C++
I want to call CreateNewScanner which creates a new scanner object and get the results in C++.
Function mentioned in the DLL is:
BOOL CreateNewScanner(NewScanner *newScan);
and NewScanner is a struct, as below,
// Structure NewScanner is defined in "common.h" .
typedef struct{
BYTE host_no; // <- host_no =0
LONG time; // <- command timeout (in seconds)
BYTE status; // -> Host adapter status
HANDLE obj; // -> Object handle for the scanner
}NewScanner;
How will I call this function? Started with C++ and here is what I managed,
#include <iostream>
#include <windows.h>
using namespace std;
int main(){
HINSTANCE hInstance;
if(!(hInstance=LoadLibrary("WinScanner.dll"))){
cout << "could not load library" << endl;
}
/* get pointer to the function in the dll*/
FARPROC handle = GetProcAddress(HMODULE(hInstance), "CreateNewScanner");
if(!handle){
// Handle the error
FreeLibrary(hInstance);
return "-1";
}else{
// Call the function
//How to call here??
}
}
First of all, return "-1" is no good. You are expected to return an integer. So you surely mean return -1.
Now to the question. Instead of declaring the function pointer as FARPROC, it's easier to declare it as a function pointer type.
typedef BOOL (*CreateNewScannerProc)(NewScanner*);
Then call GetProcAddress like this:
HMODULE hlib = LoadLibrary(...);
// LoadLibrary returns HMODULE and not HINSTANCE
// check hlib for NULL
CreateNewScannerProc CreateNewScanner =
(CreateNewScannerProc) GetProcAddress(hlib, "CreateNewScanner");
if (CreateNewScanner == NULL)
// handle error
// now we can call the function
NewScanner newScan;
BOOL retval = CreateNewScanner(&newScan);
Having said all of that, usually a library will come with a header file (yours clearly does so you should include it) and a .lib file for load-time linking. Make sure that you pass the .lib file to your linker and you can simply do this:
#include "NameOfTheHeaderFileGoesHere.h"
....
NewScanner newScan;
BOOL retval = CreateNewScanner(&newScan);
No need to mess around with LoadLibrary, GetProcAddress and so on.
If you want to follow the LoadLibrary/GetProcAddress/FreeLibrary approach, consider the following "code path" (note that if you have the DLL public header file and the corresponding .lib file, just #include the public DLL header, and link with the .lib file, and just use the function whose prototype is defined in the DLL header as you would do with an ordinary C function called from C++ code).
Define a typedef for a pointer to the function exported from the DLL.
Note that the calling convention is specified (usually, Win32 DLLs with pure-C interfaces use __stdcall calling convention):
//
// Prototype of the DLL function, with *calling convention* specified
// (usually it's __stdcall for DLL with pure-C interface).
//
typedef BOOL (__stdcall *CreateNewScannerPtr)(NewScanner *);
Then you try loading the DLL using LoadLibrary:
//
// Try loading the DLL.
//
HMODULE hDll = LoadLibrary(L"WinScanner.dll"); // <--- Note the use of L"..." for Unicode
if (! hDll)
{
.... error
}
Note that the file name of the DLL is a Unicode string (note the L"..." decoration). In general, you should use Unicode in modern C++/Win32 code.
Then you can try getting the function pointer using GetProcAddress:
//
// Try getting the pointer to CreateNewScanner DLL function.
//
auto pCreateNewScanner = reinterpret_cast<CreateNewScannerPtr>
(
GetProcAddress
(
hDll, // DLL handle
"CreateNewScanner" // Function name
)
);
if (! pCreateNewScanner)
{
.... error
// Release the DLL
FreeLibrary(hDll);
// Avoid dangling references
hDll = nullptr;
}
Note that since you are using C++, it's better using C++-style casts (like reinterpret_cast<> in this case), instead of old C-style casts.
Moreover, since the type of the function pointer is specified in reinterpret_cast, it's useless to repeat it at the beginning of the statement, so the new C++11's keyword auto can be used.
You can use the returned function pointer to call the DLL function:
BOOL retCode = pCreateNewScanner( .... );
// Note: some other common prefix used in this case is "pfn"
// as "pointer to function" (e.g. pfnCreateNewScanner).
Once you have finished using the DLL, you can release it, calling FreeLibrary:
//
// Release the DLL
//
FreeLibrary(hDll);
hDll = nullptr;
In addition, note that you can use the C++ RAII pattern, and define a class with a destructor that automatically frees the DLL (this simplifies the code that manages the library loading/releasing parts).
e.g.
class RaiiDll
{
public:
// Load the DLL.
explicit RaiiDll(const std::wstring& filename) // may also provide an overload
// with (const wchar_t*)
{
m_hDll = ::LoadLibrary(filename.c_str());
if (! m_hDll)
{
// Error
throw std::runtime_error("Can't load the DLL - LoadLibrary() failed.");
// .... or use some other exception...
}
}
// Safely and automatically release the DLL.
~RaiiDll()
{
if (m_hDll)
{
::FreeLibrary(m_hDll);
m_hDll = nullptr;
}
}
// Get DLL module handle.
HMODULE Get() const
{
return m_hDll;
}
private:
HMODULE m_hDll; // DLL instance handle
//
// Ban copy (if compiler supports new C++11 =delete, use it)
//
private:
RaiiDll( RaiiDll & );
RaiiDll & operator=( RaiiDll & );
};
Then, in some code block, you can have:
{
// Load the library (throws on error).
RaiiDll scannerDll(L"WinScanner.dll");
// Get DLL function pointer
auto pCreateNewScanner = reinterpret_cast<CreateNewScannerPtr>(
GetProcAddress(scannerDll.Get(), "CreateNewScanner"));
if (! pCreateNewScanner)
{
.... error.
}
.... use the function
} // <--- DLL automatically released thanks to RaiiDll destructor!!!
Note how code is simplified thanks to automatic invocation of RaiiDll destrutor (and so of FreeLibrary), also in the error path case.

How to access a function inside a dll file in C++

I am currently trying to communicate with a device using CAN. To do so I am using PCAN Basic using C++.
Unfortunately, I know nothing about accessing a function inside a dll file (which is what is provided). I found this link:
Calling a dll function from C++
and am trying to use LoadLibrary via code I found here:
http://www.goffconcepts.com/techarticles/development/cpp/calldll.html
My Code:
// 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;
}
However, Visual Studio says that there is a:
Unhandled exception at 0x10001D95 (Pcan_usb.dll) in dll_get_func.exe: 0xC0000005:
Access violation reading location 0x00000051.
I have Pcan_usb.dll and Pcan_usb.lib in the same folder and I am using visual studio 2012.
There are several points here. Signature of the LoadLibrary:
HMODULE WINAPI LoadLibrary(_In_ LPCTSTR lpFileName);
Remove unneeded casts. This will simplify reading and understanding your code.
FARPROC lpfnGetProcessID - the name of the variable is confusing. This might be a source of confusion or misunderstanding.
Regarding the AV - the signature of the CAN_Init function as you are trying to use it is wrong. From your post it is hard to tell for sure what is should be. Look into manual (if possible), header file, etc.
Main point - you should not release the library. There are rare cases when this is needed. Most likely your case does not need this. It is very difficult to believe that you need to reload the library (and this what happens when you call FreeLibrary/LoadLibrary!) between initing it and writing.
Access violation reading location 0x00000051.
This tells me the function is treating PCAN_USBBUS1 as a pointer. Perhaps:
#define PCAN_USBBUS1 0x51
should be changed to
WORD pcan_usbbus1 = 0x51;
And the call to CAN_Init should be changed to:
int intMyReturnVal = CAN_Init(&pcan_usbbus1, CAN_BAUD_1M);
The function signature should probably be something like:
typedef int (__stdcall * pICFUNC)(WORD* wBTR0BTR1, int CANMsgType);
^ pointer here
I imagine CAN_BAUD_1M might also need to be changed in the same way but maybe not.