简体   繁体   中英

Calling a DLL function from vba excel 64 bit

I am having a problem working with DLL functions in vba Excel 64-bit(Win8). When I force function declarations to be loaded from absolute DLL path, like below, there is no problem and my code runs well.

Private Declare PtrSafe Function get_Ith Lib "MYPATH\CVode.dll" (ByVal lpv As LongPtr, ByVal i As LongPtr) As Double

However, I don't want the absolute path. So, I put dll file next to the excel file (in the same folder) and declare function like the following:

Private Declare PtrSafe Function get_Ith Lib "CVode.dll" (ByVal lpv As LongPtr, ByVal i As LongPtr) As Double

Then I include following statements in Workbook_Open of the excel sheet.

Private Sub Workbook_Open()
  ChDrive ThisWorkbook.Path
  ChDir ThisWorkbook.Path

End Sub

I have been using this method for this dll (but newer version) as well as other projects without any problem. But right now the vba returns some irrelevant values from dll functions and my program would blow out. BTW, the dll has been written in c++ and I have the source code. In the source code there is .def file exporting all functions to external programs.
I would appreciate it if you help me out

I don't think it's the path that's causing the problem. Either you're loading the wrong DLL when you don't have the explicit path, or the DLL you're calling as a 64bit DLL is actually a 32bit DLL.

Note that because Excel does stack-fixup after you corrupt the stack by calling a DLL with the wrong declaration, you won't always see the errors you create. Make sure that pointers you declare in the DLL code are the same size as the pointers you use in 64-bit Excel.

Also make sure that your calling convention (stdcall etc.) is doing the right thing. The fact that you aren't using an Alias suggests that your calling convention should be at least looked at. ByVal looks right.

Also see Calling GetProcAddress from VBA always returns null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM