I am working in a x64 Class Library made in .NET framework 4.7.2.
This code is going to be used in MS Access with Office365, and I need to load the library into the database.
Below is the code I use to reference the dll, it is important to know that this code snippet is located in a Class Module:
Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr
Private Declare PtrSafe Function FreeLibrary Lib "kernel32" (ByVal hLibModule As LongPtr) As Long
Private Declare PtrSafe Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal GetModuleHandle As String) As LongPtr
Private Declare PtrSafe Function myFunction Lib "Path\To\dll.dll" () As Object
Of course, the Class Module has a function which declares an object to be able to call all the other functions inside the class, here is the code:
Private Function DM() As Object
On Error Resume Next
If dmObject Is Nothing Then
'load from the dll
hLibModuleID = LoadLibrary("Path\to\dll.dll")
'Debug.Print hLibModuleID
Set dmObject = myFunction()
'Debug.Print dmObject
End If
Set DM = dmObject
End Function
My problem comes in the line Set dmObject = myFunction(), because myFunction() returns Nothing and it throws the following error:
I am using MS Access x64 so obviously the dll is compiled in the corresponding platform target.
I have also installed the NuGet Package called UnmanagedExports which allows me to add the following reference:
using RGiescke.DllExport;
And its attribute:
[DllExport]
If it can help, my Visual Studio project uses PackageReference instead of the old Packages.config file.
Does anyone know how to fix this?
Thank you.

After racking my barin for hours and hours, I found the solution.
The problem was in the way I was returning my object in
MyFunction(), so, it was not a problem ofVBAcode, it was fromC#.I was doing the following:
The problem was that when I am declaring the variable
object, I cannot set it directly toMyClass, and I did this:If I declare the variable as
varit works perfect.It was an easy to solve problem, but I spent lots of hours on it.
At least I learnt something new ;)